在我的代码中找不到max和min

  发布于 2023-02-07 15:09

我写了两个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 ...等等...

1 个回答
  • 您的代码导致未定义的行为.未定义的行为意味着,任何事情都可能发生.您尚未初始化变量,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 ...等等...

    2023-02-07 15:13 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有