我如何让我的代码工作?当它不应该这样做时,循环以某种方式终止
How do I get my code to work?The loop somehow terminates when it shouldn't do so
我最近开始使用 cs50,我正在处理问题集 1,但我的代码有问题,我无法弄清楚是什么 wrong.The 问题是提示 1 到 8 之间的数字(包括的)。如果您没有输入 1 到 8(含)之间的数字,它应该会再次提示。
$ ./mario
Height: -1
Height: 0
Height: 42
Height: 50
Height: 4
我试过使用 do while 循环,但如果我输入错误的数字或正确的数字,循环就会终止。
int main(void) {
int n;
do {
printf("Height: ");
n = scanf("%d", &n);
}while(n < 1 || n > 8);
}
它应该像下面这样工作。
$ ./mario
Height: -1
Height: 0
Height: 42
Height: 50
Height: 4
Stored: 4
但这是我在 CLion 中 运行 它给出的消息。
C:\Users\acer\CLionProjects\untitled5\cmake-build-debug\hello.exe
Height:11
Process finished with exit code 0
您不需要将扫描的 return 分配给变量。
如果要从客户端扫描变量'n',只需:
scanf("%d", &n);
而不是
n = scanf("%d", &n);
关注这个link可以帮助您了解更多
https://computer.howstuffworks.com/c7.htm
我最近开始使用 cs50,我正在处理问题集 1,但我的代码有问题,我无法弄清楚是什么 wrong.The 问题是提示 1 到 8 之间的数字(包括的)。如果您没有输入 1 到 8(含)之间的数字,它应该会再次提示。
$ ./mario
Height: -1
Height: 0
Height: 42
Height: 50
Height: 4
我试过使用 do while 循环,但如果我输入错误的数字或正确的数字,循环就会终止。
int main(void) {
int n;
do {
printf("Height: ");
n = scanf("%d", &n);
}while(n < 1 || n > 8);
}
它应该像下面这样工作。
$ ./mario
Height: -1
Height: 0
Height: 42
Height: 50
Height: 4
Stored: 4
但这是我在 CLion 中 运行 它给出的消息。
C:\Users\acer\CLionProjects\untitled5\cmake-build-debug\hello.exe Height:11 Process finished with exit code 0
您不需要将扫描的 return 分配给变量。
如果要从客户端扫描变量'n',只需:
scanf("%d", &n);
而不是
n = scanf("%d", &n);
关注这个link可以帮助您了解更多 https://computer.howstuffworks.com/c7.htm