gpt4 book ai didi

c - 根据用户输入重复while循环

转载 作者:太空宇宙 更新时间:2023-11-04 06:24:47 25 4
gpt4 key购买 nike

#include<stdio.h>
void main(){
char choice1,choice2;
int a,b,c;
while(choice1 != 'n'){
printf("Enter + for addition:\n");
printf("Enter - for substraction:\n");
printf("Enter * for multiplication:\n");
printf("Enter / for division:\n");
scanf("%c",&choice2);
printf("Enter two numbers:\n");
scanf("%d %d",&a,&b);
if (choice2 == '+'){
c=a+b;
printf("Addition = %d",c);
}
else if (choice2 == '-'){
c=a-b;
printf("Substraction = %d",c);
}
else if (choice2 == '*'){
c=a*b;
printf("Multiplication = %d",c);
}
else if (choice2 == '/'){
c=a/b;
printf("Division = %d",c);
}
else{
printf("Invalid choice!");
}
printf("\nEnter y to continue and n to exit:\n ");
scanf("%c",&choice1);
}
}

当我运行上面的程序时,while 循环重复而不从用户那里获取 choice1 的值。谁能告诉我上面的代码有什么问题???

最佳答案

choice1 在表达式 choice1 != 'n' 中进行比较而不进行初始化。使用 do while 循环代替或如下更改它

scanf(" %c",&choice1);
while(choice1 != 'n'){
// Loop body

scanf(" %c",&choice1); // Do not forget to add a space before %c to skip newline
//characters left behind by previous call to scanf.
}

关于c - 根据用户输入重复while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544577/

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