c - 无论输入如何,Min 函数都会给出输出 6422164

标签 c

我想实现一个返回最少四个元素的函数。我写了以下代码:

#include <stdio.h>

int max_of_four(int a, int b, int c, int d) {
  int max;

  if (a > b) {
    if (a > c) {
      if (a > d) {
        max = a;
      }
    }
  } else if (b > a) {
    if (b > c) {
      if (b > d) {
        max = b;
      }
    }
  } else if (c > a) {

    if (c > b) {
      if (c > d) {
        max = c;
      }
    }
  } else {
    max = d;
  }
  return max;
}

int main() {
  // initializing int a, b, c, d, max;
  scanf("%d %d %d %d", &a, &b, &c, &d);
  int ans = max_of_four(a, b, c, d);
  printf("%d", ans);

  return 0;
}

无论输入如何,这段代码都会给我输出 6422164。我的代码有什么问题?

最佳答案

您没有正确涵盖这些案例,例如如果 a=1b=2c=3 会怎样。第二个 if (b>a) 中的条件为真,进入 block 。那么条件 b>c 将是 false 并且不会进入其他 block 。最后返回 uninitialised 变量 max,返回一个未定义的值,您看到的值为 6422164。

更好的写法是将 max 初始化为第一个值,然后将每个值依次与 max 进行比较,如果当前数字大于则更新它最大。

int max_of_four(int a,int b,int c,int d) {
    int max = a;

    if (b > max) max = b;
    if (c > max) max = c;
    if (d > max) max = d;

    return max;
}

关于c - 无论输入如何,Min 函数都会给出输出 6422164,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66085884/

相关文章:

c - 非阻塞读永不返回

c - 从关联指针数组中逐字符读取字符串

字符指针 : Creating dynamic string array, 赋值并传递给其他函数和其他小家伙 - C

c - C中未初始化的指针到底有什么危险

c++ - 获取 char* 缓冲区中的第一个字节

c - glUseProgram 是否有任何原因可能导致我的程序崩溃? (C Win32)

c - 十进制转十六进制 : issues with sprintf?

c - 使用本地工作组的 OpenCL 中值图像滤波器

c - 如何让我的 Eclipse CPP 月球显示输出?

c - 将字符串回显到 powershell 中的 c 程序