【发布时间】:2022-12-02 04:01:03
【问题描述】:
I am trying to write a calculator using functions for each operation and switch case in c language but i can't seem to call functions inside cases. thanks in advance. `
#include <stdio.h>
#include <math.h>
float addTwoNumbers(float num1, float num2);
float subtTwoNumbers(float num1, float num2);
float divideTwoNumbers(float num1, float num2);
float multTwoNumbers(float num1, float num2);
float powerTwoNumbers(float num1, float num2);
int main() {
float num1, num2,add,subt,div,mult,pow;
int choice;
printf("choose one operation:\n 1.addition\n 2.substraction\n 3.division\n 4.multiplication\n 5.power\n");
scanf("%d" ,&choice);
printf("Enter two numbers: ");
scanf("%f %f" ,&num1,num2);
add=addTwoNumbers(num1, num2);
subt=subtTwoNumbers(num1, num2);
div=divideTwoNumbers(num1, num2);
mult=multTwoNumbers(num1, num2);
pow=powerTwoNumbers(num1, num2);
switch (choice) {
case 1:
add = addTwoNumbers(num1, num2);
printf("%f + %f = %f" ,num1,num2,add);
break;
case 2:
subt = subtTwoNumbers(num1, num2);
printf("%d - %d = %d" ,num1,num2,subt);
break;
case 3:
div = divideTwoNumbers(num1, num2);
printf("%d / %d = %d" ,num1,num2,div);
break;
case 4:
mult = multTwoNumbers(num1, num2);
printf("%d * %d = %d" ,num1,num2,mult);
case 5:
pow = powerTwoNumbers(num1, num2);
printf("%d ? %d = %d" ,num1,num2,pow);
break;
default:
printf("Error!");
}
return 0;
}
float addTwoNumbers(float num1, float num2)
{
return num1+num2;
}
float subtTwoNumbers(float num1, float num2)
{
float result2;
result2 = num1-num2;
return result2;
}
float divideTwoNumbers(float num1, float num2)
{
printf("s");
}
float multTwoNumbers(float num1, float num2)
{
printf("s");
}
float powerTwoNumbers(float num1, float num2)
{
printf("s");
}
`
i might be giving the type of inputs wrong. when i change float to int, my program outputs numbers like 39431845 instead of printing 5 for example and finds 5+2=0 (not the exact results but similar). when i use float it just doesn't output anything. I wanted to call functions inside cases.
【问题讨论】:
-
Why are you using
%din someprintfstatements? That's for integers. Use%fforfloat. -
Look closely at this line:
scanf("%f %f" ,&num1,num2);One param has a&, the other does not. -
sorry i forgot to change them but when i use %f in all of them, it still doesn't work.
-
@DilaraA Show themost correctcode that you have that is not working. Not some stale version which you know have bugs.
-
Best to not re-use
powas a variable aspow()is a<math.h>function. Use another name.
标签: c function switch-statement case calculator