简体   繁体   English

C-如何通过直接输入数字和字符(符号)字符串来创建计算器?

[英]C - How to create calculator by directly inputting a string of numbers and characters(signs)?

INPUT 1+2-3+4 OUTPUT = 4 输入1 + 2-3 + 4输出= 4

INPUT 1+2+3+4 OUTPUT = 10 输入1 + 2 + 3 + 4输出= 10

INPUT -1-2-3-4 OUTPUT = -10 输入-1-2-3-4输出= -10

Here's my attempt but i gives wrong result 这是我的尝试,但我给出了错误的结果

Code fragment: 代码片段:

for(i=0;i<strlen(res)+1;i++){
    if(res[i]=='-'||res[i]=='+'||res[i]=='\0'){
        num[z]='\0';
        dig=atoi(num);
        if(x==0){
            sum=dig;
            x++;
        }
        else{
            if(res[i]=='+')
                sum=sum+dig;
            else if(res[i]=='-')
                sum=sum-dig;
        }
        z=0;

    }
    else{
        num[z]=res[i];
        z++;
}
return sum;

I'd add print statements to the code to see where it's going wrong. 我将在代码中添加打印语句,以查看出错的地方。 But offhand it looks like when you get to the terminating null ( res[i]=='\\0' ) you don't add the final number to sum . 但是随便看来,当您到达终止null( res[i]=='\\0' )时,您并没有将最终数字加到sum

I'm making assumptions about the declarations and initializers of num, x and z and that the missing } is where the indentation implies. 我对num,x和z的声明和初始化程序进行了假设,而}就是缩进所暗示的位置。

This line references the array "num", but not the correct index: 此行引用数组“ num”,但不是正确的索引:

    dig=atoi(num);

It should be fixed if you changed it to: 如果将其更改为:

    dig=atoi(num[z-1]);

Your solution however doesn't work for calculations with numbers more than one digit long. 但是,您的解决方案不适用于数字长度超过一位数的计算。

But offhand it looks like when you get to the terminating null ( res[i]=='\\0' ) you don't add the final number to sum . 但是随便看来,当您到达终止null( res[i]=='\\0' )时,您并没有将最终数字加到sum

That's true, but not the only error; 没错,但这不是唯一的错误。 if a + or - is encountered, the corresponding addition or subtraction is done with the previous instead of the next number. 如果遇到+- ,则使用前一个数字而不是下一个数字进行相应的加法或减法。 So the input 1+2-3+4 actually computes 1-2+3 , which gives 2 . 因此,输入1+2-3+4实际上计算出1-2+3 ,得出2
You can code your whole loop much simpler using strtol : 您可以使用strtol简化整个循环的代码:

    char *beg, *end = res;
    for (sum = 0; dig = strtol(beg = end, &end, 0), end-beg; ) sum += dig;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM