2013-06-20 16 views
0

我想在C中创建一个简单的计算器。我目前只有一个问题,那就是当我尝试将运算符值分配给输入的值时,将其存储在一个字符数组中,但它会分配它,但当我退出for循环不再分配。我曾尝试使用malloc,但这不起作用。由于事先值不分配给变量? C计算器

int calculator() 
{ 
int exit; 
exit = 1; 
while(exit == 1){ 

    printf("Welcome to the calculator, please enter the calculation you wish to make, if you wish to exit type EXIT\n"); 

    float num1; 
    float num2; 
    char operation; 
    float ans; 
    char string[10]; 
    int beenhere = 0; 

    scanf("%s", &string); 
    int result = strncmp(string, "EXIT", 10); 

    if(result == 0){ 
     exit = 0; 
    } 
    else{ 
     int length = strlen(string); 
     int i; 
     for(i = 0; i <= length; i++){ 
      if(isdigit(string[i]) != 0){ 
       if(beenhere == 0){ 
        num1 = (float)string[i] - '0'; 
        beenhere = 1; 
       } 
       else{ 
        num2 = (float)string[i] - '0'; 
       } 
      } 
      else{ 
       operation = string[i]; 
      } 
     } 
     printf("num1 %f\n", num1); 
     printf("%c\n", operation); 
     printf("num2 %f\n", num2); 

     if(operation == '+'){ 
      ans = num1 + num2; 
     } 
     if(operation == '-'){ 
      ans = num1 - num2; 
     } 
     if(operation == '/'){ 
      ans = num1/num2; 
     } 
     if(operation == '*'){ 
      ans = num1 * num2; 
     } 
     if(operation == '^'){ 
      ans = (float)pow(num1,num2); 
     } 

     printf("Your answer is %f\n", ans); 

     } 
} 
return 0; 

}

编辑:我指的是for循环,其中,所述分配是:操作=串[I];

+0

你指的是哪个循环? – user2407394

回答

2

你的问题是在for循环:

for(i = 0; i <= length; i++){ 

由于长度为strlen(..),你不能有长度,但length-1

你正在做一个额外的循环,它的char为0,将你的指令设置为空值 - 即空字符串。

你的循环更改为:

for(i = 0; i < length; i++){ 
+0

谢谢,多么愚蠢的错误! – Coolmurr

+0

那些始终是难以发现的! – craigmj

1

变化

for(i = 0; i <= length; i++) 

for(i = 0; i < length; i++)