我已经为最大值和最小值编写了两段代码。第一个没有,第二个有额外功能。
第一个有效,但第二个最小值始终为 1。为什么?
是什么导致了问题?
(1) 没有函数的代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int x,n,min=x,max=1,cnt;
while(1){
cnt=0;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
printf("enter your numbers\n");
while (cnt!=n){
scanf("%d",&x);
cnt++;
if(x>max)
max=x;
if(x<min)
min=x;
}
printf("maximum is:%d\n",max);
printf("minimum is:%d",min);
getch();
system("cls");
}
return 0;
}
(2) 功能代码:
#include <stdio.h>
#include <stdlib.h>
int maximum(int);
int main(int argc, char *argv[]) {
int n;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
maximum(n);
return 0;
}
//*****************************************
int maximum(int n){
int i,a,max=1,min=a;
printf("enter your number\n");
for(i=1;i<=n;i++){
scanf("%d",&a);
if(a>max)
max=a;
if(a<min)
min=a;
}
printf("maximum is:%d\n",max);
printf("minimum is:%d",min);
getch();
}
最佳答案
您的代码会导致未定义的行为。未定义的行为意味着,任何事情都可能发生。
您尚未初始化变量 a
而您正在执行 min=a;
C99 6.7.8 节初始化:
If an object that has automatic storage duration is not initialized explicitly,
its value is indeterminate.
C99 第 3.18 节未定义的行为:
Behavior, upon use of a non-portable or erroneous program construct, of erroneous
data, or of indeterminately valued objects, for which this International Standard
imposes no requirements.
这意味着,编译器可以自由地做任何事情。它可能会使您的程序崩溃,您的程序可能会在您的显示器上打印 JLo 图片...等等...
关于在我的代码中找不到最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20839708/