值不分配给变量?C计算器



我试图在c中创建一个简单的计算器。我目前只有一个问题,那就是当我尝试将我的操作符值分配给输入的值时,存储在字符数组中,它分配给它,但是当我退出for循环时不再分配。我试过使用malloc,但这不起作用。提前感谢

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 EXITn");
    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 %fn", num1);
        printf("%cn", operation);
        printf("num2 %fn", 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 %fn", ans);
        }
}
return 0;

}

编辑:我指的是forloop,其中赋值是:operation = string[I];

你的问题在for循环中:

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

由于length是strlen(..),所以不能到达length,只能到达length-1

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

将循环改为:

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

change

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

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

相关内容

最新更新