gpt4 book ai didi

c - 某些字符存在格式问题,但其他字符则正常

转载 作者:行者123 更新时间:2023-11-30 16:12:10 25 4
gpt4 key购买 nike

我正在尝试编写的这个计算器有几个问题。不能 100% 确定这是格式化还是其他原因。第一个问题是,使用 + 和 -、C(清除)和 T 将累加器设置为以下数字后,它不会打印结果。它在 * 和/上运行良好。另一个问题是我保存所有输入的数组的打印。它对于某些输入工作正常,但格式很奇怪。有些字符不会显示,有些 float 是错误的,有些是正确的。我希望有人能为我解决这个问题。

我尝试过进行一些小的调整,但这已经非常接近我的目标了。

int main(){
float tall[STRLEN], input,
akkumulator = 0.0;
char tegn[STRLEN], operator;
int i = 0;

printf("Kalkulator\n");
printf("= %f", akkumulator);
do{

i += 1;
printf("\n: ");
scanf("%c", &operator); char check = toupper(operator);
scanf("%f", &input);

switch (check){
case '*':
akkumulator *= input;
tegn[i] = '*';
tall[i] = input;
printf("\n= %f", akkumulator);
break;
case '+':
akkumulator += input;
tegn[i] = '+';
tall[i] = input;
printf("\n= %f", akkumulator);
break;
case '-':
akkumulator -= input;
tegn[i] = '-';
tall[i] = input;
printf("\n= %f", akkumulator);
break;
case '/':
akkumulator /= input;
tegn[i] = '/';
tall[i] = input;
printf("\n= %f", akkumulator);
break;
case 'C':
akkumulator = 0.0;
tegn[i] = 'C';
tall[i] = input;
printf("\n= %f", akkumulator);
break;
case 'T':
akkumulator = input;
tegn[i] = 'T';
tall[i] = input;
printf("\n= %f", akkumulator);
break;
default:
break;
}

if(tegn[i] == '/' && tall == 0)
printf("\n You can not do that");
else if(operator == 'S')
for(int y = 0; y<i; y++){
printf("\n%2c %5f", tegn[y], tall[y]);
}

}while(operator != 'S');


return 0;
}

最佳答案

在开始之前,在这种情况下,for循环会比 do while() 有帮助得多环形。对于除以零,您已经有 case '/': ,所以如果你输入 printf("\n You can not do that"); 会更好在switch .

  1. 您有两个scanf() s 在循环的开头,这意味着您需要将输入像
C
13.45

继续循环。此外,即使你输入两个像

C
45.23

,下一个 scanf for 操作符得到 \n由于您的输入缓冲区。添加getchar()之后scanf("%f", &input);将解决这个问题。最后,你的do while()循环的终止条件是operator != 'S' ,然而operator仍然's'因为大写字母的变化是 check ,不是operator 。这就是为什么即使您输入 s,计算器也不会结束的原因。

  • 您将从 i = 1 开始将运算符和输入值保存在数组中,同时从零开始打印数组。改变
  • for(int y = 0; y<i; y++){
    printf("\n%2c %5f", tegn[y], tall[y]);
    }

    进入

    for(int y = 1; y <= i; y++){
    printf("\n%2c %5f", tegn[y], tall[y]);
    }

    将解决您的问题

    关于c - 某些字符存在格式问题,但其他字符则正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58398988/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com