I tried to create a simple calculator in C, but when i started it with all the operations the results is 0, the code is this:
#include <stdio.h>
/*
Author: Ermanno Oliveri
Date: 14/11/2021
Description: Simple Calculator
*/
int main(){
float n1, n2, ris;
int choice;
n1 = 0;
n2 = 0;
ris = 0;
choice = 0;
printf("Insert the first Number: \n");
scanf("%f", &n1);
printf("Insert the second Number: \n");
scanf("%f", &n2);
printf("enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division \n");
scanf("%d", &choice);
switch (choice){
case 1:
ris = n1 n2;
printf("\nThe result is: %f", &ris);
break;
case 2:
ris = n1 - n2;
printf("\nThe result is: %f", &ris);
break;
case 3:
ris = n1 * n2;
printf("\nThe result is: %f", &ris);
break;
case 4:
if (n2 == 0){
printf("Impossible division");
}
else {
ris = n1 / n2;
printf("\nThe result is: %f", &ris);
}
break;
default:
printf("VALUE NOT VALID");
}
}
I also tried to execute some parts of the code individually, also trying the scanf but the result is always the same.
Since I am a beginner I could not find the problem.
I thank you in advance
CodePudding user response:
The second argument to printf
should not be a pointer, it should just be ris
without the &
. A good compiler will warn you about this so make sure compiler warnings are enabled and you are looking at them.
CodePudding user response:
you should remove & from printf
printf("\nThe result is: %f",ris);
modified version:
#include <stdio.h>
/*
Author: Ermanno Oliveri
Date: 14/11/2021
Description: Simple Calculator
*/
int main(){
float n1, n2, ris;
int choice;
n1 = 0;
n2 = 0;
ris = 0;
choice = 0;
printf("Insert the first Number: \n");
scanf("%f", &n1);
printf("Insert the second Number: \n");
scanf("%f", &n2);
printf("enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division \n");
scanf("%d", &choice);
switch (choice){
case 1:
ris = n1 n2;
printf("\nThe result is: %f", ris);
break;
case 2:
ris = n1 - n2;
printf("\nThe result is: %f", ris);
break;
case 3:
ris = n1 * n2;
printf("\nThe result is: %f", ris);
break;
case 4:
if (n2 == 0){
printf("Impossible division");
}
else {
ris = n1 / n2;
printf("\nThe result is: %f", ris);
}
break;
default:
printf("VALUE NOT VALID");
}
}