while循环 - 改变字符串变量

时间:2015-02-17 21:28:45

标签: c string while-loop

作为c编程的新手(我只有Visual Basic的经验),我不完全确定在条件语句中带有更改字符串变量的while循环应该如何运行。

以下代码是我正在制作的一个简单的计算器,允许用户输入操作和两个数字,然后输出相应的结果。我试图在while循环中编码,不断重复该过程,直到用户决定退出它。然而似乎行scanf(“%c”,& quit);不影响while循环条件语句。

#include <stdio.h>

int main() {
float num1, num2;
char operation;
char quit = "n";
while (quit = "n"){
printf("Enter an operator (+, -, *, /) \n");
scanf(" %c", &operation);
printf("Enter the numbers you wish to carry out the operation on \n");
scanf("%f %f", &num1, &num2);
    switch(operation) {
        case '+':
            printf("%f\n", num1+num2);
            break;
        case '-':
            printf("%f\n", num1-num2);
            break;
        case '*':
            printf("%f\n", num1*num2);
            break;
        case '/':
            printf("%f\n", num1/num2);
            break;

    }
printf("Would you like quit the program, is so enter 'y' \n");
scanf("%c", &quit);
}
return 0;
}

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

你可以这样做

#include <stdio.h>
int main() {
float num1, num2;
char operation;
char quit = 'n';
//while (quit = "n") //
  while (quit!= 'y')
 {
printf("Enter an operator (+, -, *, /) \n");
scanf(" %c", &operation);
printf("Enter the numbers you wish to carry out the operation on \n");
scanf("%f %f", &num1, &num2);
switch(operation) {
    case '+':
        printf("%f\n", num1+num2);
        break;
    case '-':
        printf("%f\n", num1-num2);
        break;
    case '*':
        printf("%f\n", num1*num2);
        break;
    case '/':
        printf("%f\n", num1/num2);
        break;

}
printf("Would you like quit the program, is so enter 'y' \n");
scanf("%c", &quit);
 }
return 0;
}

答案 1 :(得分:-1)

while (quit = "n")替换为while (quit! = 'y')

答案 2 :(得分:-2)

那是因为你在while循环中分配了quit变量的值,而不是检查它的值。

使用== for =

while(quit == "n"){...}