Я также пытался применить свое знание C в простой калькулятор и наткнулся на вас вопросом. Чтобы уважать ваш запрос if ... else, я придумал это решение. Надеюсь, это поможет.
#include <stdio.h>
void sayHello() {
printf("Hello\n"); }
// to say hello to the user
int add(int num1, int num2) {
num1 = num1 + num2;
return num1;
}
int minus(int num1, int num2) {
num1 = num1 - num2;
return num1;
}
int times(int num1, int num2) {
num1 = num1 * num2;
return num1;
}
int divide(int num1, int num2) {
num1 = num1/num2;
return num1;
}
// This is to declare the calculations
void flush_input(){
int ch;
while ((ch = getchar()) != '\n' && ch != EOF); }
// This is to flush the scanf values
// Kudos to Huw Collingbourne, Udemy Teacher
int main(int argc, char **argv) {
char c;
char f;
int n1;
int n2;
int total;
// n1 = ' ';
// n2 = ' ';
sayHello();
do {
c = ' ';
printf("Insert the type of Calculation you want to make:\n");
printf("A(d)dition, Subs(t)raction, Mu(l)tiplication, Di(v)ision: ");
c = getchar();
if(c == 'd') {
printf("\nInsert the first number:");
scanf("%d", &n1);
printf("Insert the second number:");
scanf("%d", &n2);
total = add(n1, n2);
printf("%d plus %d equals to %d\n", n1, n2, total);
flush_input(); } else {
if(c == 't') {
printf("insert the base number:");
scanf("%d", &n1);
printf("Insert the subtracting number:");
scanf("%d", &n2);
total = minus(n1, n2);
printf("The difference between %d and %d is %d\n", n1, n2, total);
flush_input(); } else {
if(c == 'l') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = times(n1, n2);
printf("%d times %d equals %d\n", n1, n2, total);
flush_input(); } else {
if(c == 'v') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = divide(n1, n2);
printf("%d divided by %d equals %d\n", n1, n2, total);
flush_input();
} else {
printf("I couln't understand the instruction\n Reseting program\n");
}
}
}
}
f = ' ';
printf("\nDo you wish to make another calculation?\n");
printf("Choose (y)es or (n)ot: ");
f = getchar();
// scanf("%c", &c);
getchar();
} while(f != 'n');
printf("\nThat's all folks!\n");
return 0;
}
Операция не имеет значения, которое, по вашему мнению, имеет значение. Попробуйте распечатать, что это такое, что приведет вас к решению. – ChrisInEdmonton
как? например: printf («Escolha a operacao que quer realizar% c \ n \ n», oper); scanf ("% c", &oper); – Dimitri
O_O НЕ МИГРАТ CRAP! – bjb568