嗨,我再次发现自己陷入了编码困境。我找到了正确的代码,但我不明白为什么我的初始编码不起作用。谁能简单解释一下这个问题吗?
我的初始代码和可运行的代码发布在下面。
初始代码(未按预期工作)
#include <stdio.h>
#include <conio.h>
int main(void)
{
int counter;
int num1, num2, smallest;
counter = 1;
printf("Enter first number:");
scanf("%d", &num1);
smallest = num1;
while (counter <= 10) // User input phase
{
printf("Enter next numer:");
scanf("%d", &num2);
if (num1 < num2)
{
smallest = num1;
}
if (num2 < num1)
{
smallest = num2;
}
counter++;
}
printf("Smallest is %d", smallest);
getch();
}
可运行的代码
#include <stdio.h>
#include <conio.h>
int main(void)
{
int counter;
int num1, smallest;
counter = 1;
printf("Enter first number:");
scanf("%d", &num1);
smallest = num1;
while (counter <= 10) // User input phase
{
printf("Enter next numer:");
scanf("%d", &num1);
if (num1 < smallest)
{
smallest = num1;
}
if (smallest < num1)
{
smallest = smallest;
}
counter++;
}
printf("Smallest is %d", smallest);
getch();
}
最佳答案
在第一次尝试中,您保存了每个循环中最小的值,但您将其删除,因为下一个循环将始终检查 num1
和 num2
中新输入的数字>.
在第二个代码(工作代码)中,循环跟踪找到的最后一个最小的值。
一点小事,代码块
if (num1 < smallest)
{
smallest = num1;
}
if (smallest < num1)
{
smallest = smallest;
}
第二个if
没有意义,可以这样写
if (num1 < smallest)
{
smallest = num1;
}
else
{
smallest = smallest;
}
或更好
if (num1 < smallest)
{
smallest = num1;
}
关于C 程序 - While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32586959/