我做了一个显示最小值和最大值的 C do while 循环。当用户输入 0 时,循环结束。
我的问题是当我输入一组都大于 0 的数字时,我的最小值为零。
例如,当我输入时
19,16,8,12,9
我的max is 19
,但我min is 0
。
我需要min
是集合的min
,所以在这种情况下是 8。
我也有集合负整数的问题
-6,-4,-9,-12
min is -12
,但我max is 0
.在这种情况下,我想要我的max to be -4
。
我该如何解决这个问题。这是因为我必须输入 0 才能结束程序吗?我应该尝试一个while循环吗?
任何帮助,不胜感激。
#include<stdio.h>
main()
{
int L,S,X;
do{
printf("ninput number:");
scanf("%d",&X);
if (X>L){
L=X;
}
if (X<S){
S=X;
}
} while(X!=0);
printf("nmax %d, min %d",L,S);
printf("n");
return 0;
}
你的变量L
和S
是未初始化的,所以从一些未知值开始。 最小值应从 INT_MAX 开始,最大值应从 INT_MIN 开始。
首先扫描一个值并将其存储在 L 和 S 中,并添加一个 if 来检查第一个数字本身是否为 0
#include<stdio.h>
main() {
int L,S,X;
printf("ninput number:");
scanf("%d",&X);
L=X;
S=X;
if(X!=0){
do{
printf("ninput number:");
scanf("%d",&X);
if (X>L){
L=X;
}
if (X<S){
S=X;
}
}while(X!=0);}
printf("nmax %d, min %d",L,S);
printf("n");
return 0;
}
您必须分别使用最小值和最大值初始化L
和S
变量。由于L
和S
都是整数,因此将L
的值设置为INT_MIN
,将S
设置为INT_MAX
(这些常量存在于<limits.h>
中)。
因此,您的代码将是:
#include <stdio.h>
#include <limits.h>
main()
{
int L = INT_MIN ,S = INT_MAX , X;
printf("nInput number:");
scanf("%d",&X);
while (X)
{
if (X>L){
L=X;
}
if (X<S){
S=X;
}
printf("nInput number:");
scanf("%d",&X);
}
printf("nmax %d, min %d",L,S);
printf("n");
return 0;
}
此代码也解决了0
问题。因为,当您输入数字时,下一条语句会检查数字是否0
。