我写了两个max和min的代码.第一个是没有,第二个是额外的功能.第一个工作,但第二个最小总是1.为什么?
是什么原因造成的?
(1)无功能的代码:
#include#include 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 (2)功能代码:
#include#include 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
小智.. 6
您的代码导致未定义的行为.未定义的行为意味着,任何事情都可能发生.您尚未初始化变量,
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 pic ...等等...
您的代码导致未定义的行为.未定义的行为意味着,任何事情都可能发生.您尚未初始化变量,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 pic ...等等...