嘿,我是学习如何使用C编程的新手,我在计算器的分区部分遇到了麻烦。我需要让它浮动并有2位小数。我想我需要使用%f而不是%d,但是当我更改变量时它会中断。粉丝是浮动的答案。
这是整个代码。该部门是案例4。
#include <stdio.h>
#include <math.h>
int menu(void);
int main(void){
int selection, num1, num2, ans;
float fans;
selection = menu();
while (selection !=8) {
switch (selection) {
case 1: printf("Enter 1st number: ");
scanf("%d", &num1);
printf("Enter 2nd number: ");
scanf("%d", &num2);
ans = num1 + num2;
printf("%d + %d = %d\n", num1, num2, ans);
break;
case 2: printf("Enter 1st number: ");
scanf("%d", &num1);
printf("Enter 2nd number: ");
scanf("%d", &num2);
ans = num1 - num2;
printf("%d - %d = %d\n", num1, num2, ans);
break;
case 3: printf("Enter 1st number: ");
scanf("%d", &num1);
printf("Enter 2nd number: ");
scanf("%d", &num2);
ans = num1 * num2;
printf("%d * %d = %d\n", num1, num2, ans);
break;
case 4: printf("Enter 1st number: ");
scanf("%d", &num1);
printf("Enter 2nd number: ");
scanf("%d", &num2);
if(num2 != 0) {
fans=(float)num1/num2;
printf("%d / %d = %d\n", num1, num2, ans);
}
else {
printf("Error. Cannot divide by 0!\n");
}
break;
case 5: printf("Enter number: ");
scanf("%d", &num1);
ans=abs(num1);
printf("|%d| = %d\n", num1, ans);
break;
case 6: printf("Enter number: ");
scanf("%d", &num1);
if(num1<0) {
printf("Error. Cannot be a negative number.\n");
}
else {
fans=sqrt(num1);
printf("Sqrt(%d)=%d\n", num1, ans);
}
break;
case 7: printf("Enter base number: ");
scanf("%d", &num1);
printf("Enter exponent: ");
scanf("%d", &num2);
if((num1==0)&&(num2<=0)){
printf("Error. Power cannot be represented.\n");
}
else {
fans=pow(num1,num2);
printf("%d^%d=%d\n", num1, num2, ans);
}
break;
default:printf("%d is not a valid selection\n", selection);
}
selection=menu();
}
printf("Bye!\n");
}
int menu(void) {
int choice;
printf("1 Add\n");
printf("2 Subtract\n");
printf("3 Multiply\n");
printf("4 Divide\n");
printf("5 Absolute Value\n");
printf("6 Square Root\n");
printf("7 Powers\n");
printf("8 Quit\n");
scanf("%d", &choice);
return choice;
}
答案 0 :(得分:1)
你很亲密;你打算使用fans
,因为你知道它是一个浮动答案,你计算了前一行,但是错字或者忘了使用它。
您正确使用%f
:
printf("%d / %d = %f\n", num1, num2, fans);
注意:%.2f
也适用于2位精度; %f
有效但打印6位小数。请参阅printf()
的POSIX规范:
f
- double
- 如果没有给出精度,则打印浮点数,默认精度为6;小写。
顺便说一下,好的计算器程序:)