-1
嘿,我是學習如何使用C編程的新手,我在計算器的部分部分遇到問題。我需要它浮動並有2個小數位。我想我需要使用%f而不是%d,但是當我更改變量時它會中斷。球迷是浮動答案。Float Division計算器
以下是整個代碼。該部門是案例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;
}
也許'fans =(float)num1/num2; printf(「%d /%d =%d \ n」,num1,num2,ans);' - >'fans =(float)num1/num2; printf(「%d /%d =%.2f \ n」,num1,num2,fans);'? – chux
只接受整數輸入的計算器非常沒用。如果你想劃分2.5乘5,會發生什麼? –