我正在创建一个小程序,它使用while循环来要求用户输入大于0的数字。当程序运行时,只有循环工作,但我没有看到最大的数字。这是代码:
#include <stdio.h>
int main(void) {
int num1;
int biggestValue = 0;
printf("Enter a number: ");
scanf("%d", &num1);
while (num1 != 0) {
printf("Enter a number (0 to exit): ");
scanf("%d", &num1);
biggestValue = num1;
if (biggestValue > num1) {
printf("Biggest value is: %d \n", biggestValue);
}
}
}
答案 0 :(得分:1)
使用此代码
#include <stdio.h>
int main(void)
{
int num1;
int biggestValue = 0;
printf("Enter a number: ");
scanf("%d", &num1);
while (num1 != 0)
{
if (biggestValue < num1)
{
biggestValue = num1;
}
printf("Enter a number (0 to exit): ");
scanf("%d", &num1);
}
printf("Biggest value is: %d \n", biggestValue);
}
说明:
num1
是否大于biggestValue
。num1
大于biggestValue
,则biggestValue=num1
。biggestValue
保持不变。biggestValue
。答案 1 :(得分:1)
在显示biggestValue
之前不要设置 // biggestValue = num1;
if (num1 > biggestValue) {
biggestValue = num1; // move here
printf("Biggest value is: %d \n", biggestValue);
}
。
更改比较订单@Zaman
#include <limits.h>
#include <stdio.h>
int main(void) {
int biggestValue = INT_MIN;
const char *prompt = "Enter a number: ";
for (;;) {
fputs(prompt, stdout);
int num1;
if (scanf("%d", &num1) != 1) break;
if (num1 > biggestValue) {
biggestValue = num1;
}
prompt = "Enter a number (or 'q' to exit): ";
}
printf("Biggest value is: %d \n", biggestValue);
return 0;
}
示例完整解决方案:
\((.+?)(?<!\\)\)
答案 2 :(得分:0)
由于您正在设置biggestValue = num1;
,然后立即检查是否biggestValue > num1
,biggestValue
永远不会大于num1
。他们永远是平等的。
我认为你想要的是:
if (biggestValue < num1) {
biggestValue = num1;
}
然后在while循环之外放置:
printf("Biggest value is: %d \n", biggestValue);
答案 3 :(得分:0)
打印应该在while循环之后,并且在比较之前不要写biggestValue = num1;
。
#include <stdio.h>
int main(void)
{
int num1;
int biggestValue = 0;
while (num1 != 0)
{
printf("Enter a number (0 to exit): ");
scanf("%d", &num1);
if (biggestValue < num1)
{
biggestValue = num1;
}
}
printf("Biggest value is: %d \n", biggestValue);
}