在我的代码中找不到最大值和最小值

标签 c

我已经为最大值和最小值编写了两段代码。第一个没有,第二个有额外功能。 第一个有效,但第二个最小值始终为 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/

相关文章:

c++ - 在 C++/C 中查找文件的一部分的大小?

c - 我需要知道我是否正确使用 getline

c - 在 Linux 中关闭(或以其他方式操作)LCD

c - Visual c中的错误LNK2010,无法调用其他项目文件中的方法

c - 将CLIPS嵌入到C语言中时,可以使用什么函数来修改C程序中的事实

c - 将参数传递给 C 中的信号处理程序

c - 在 Linux 上的 C 程序中从套接字描述符获取 struct socket*、struct sock *

c++ - 手动检查套接字连接是否那么重要?

c - 访问静态变量值

c - 带有 switch 语句的 while 循环不退出