2016-09-22 68 views
-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; 
} 
+0

也许'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

+1

只接受整数输入的计算器非常没用。如果你想划分2.5乘5,会发生什么? –

回答

1

你非常接近;你打算使用fans,因为你知道这是一个浮动答案,你计算在上一行,但错字或忘记使用它。

你说得对使用%f

printf("%d/%d = %f\n", num1, num2, fans); 

注:%.2f还将为2位精度工作; %f有效,但可打印6位小数。请参阅POSIX规范printf()

f - double - 如果未给出精度,则打印默认精度为6的浮点数;小写。

顺便说一句,好的计算器程序:)