c - 最大和最小 - 哨兵控制的重复

标签 c max minimum sentinel

我必须使用哨兵控制的重复来找到最大值和最小值。

“maximum”无法正常工作。任何人都可以帮助我了解我的代码中的问题吗?

#include<stdio.h>

int main() { 
  int number;
  int min;
  int max;

  do {
    printf("Enter a number (-1 to quit): ");
    scanf("%d",&number);
    if( number >= 0 ) {
      if(number < min )
        min = number;
      if( number > max )
        max = number;

    }
    else if( number < 1 )
      printf("the number is not valid \n");
  } 

  while( number != -1 );

  printf("Minimum=%d\n",min);
  printf("Maximum=%d\n",max);

  system("pause");

  return 0;
}

最佳答案

未初始化的变量的值为 2674276,所有数字都较小,因此您的最小值很好

但没有比这个更大的数字,所以这是你的最大值。

您需要使用第一个数字初始化最小值和最大值

我会做类似的事情

max = -1
min = -1

do {
    printf("Enter a number (-1 to quit): ");
    scanf("%d",&number);
    if( number >= 0 ) {
      if(max == -1)
      {
         max = number //Means it's the first time so your max and min are the first number
         min = number
      }
      else
      {
         if(number < min )
            min = number;
         if( number > max )
          max = number;

      }
    }
    else if( number < 1 )
      printf("the number is not valid \n");
  } 

  while( number != -1 );

关于c - 最大和最小 - 哨兵控制的重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13257938/

相关文章:

algorithm - 解决具有某些约束的极小极大路径问题

java - 查找二维数组中的最大数字索引

c - 如果 C11 关键字 '_Atomic' 后跟空格和左括号,是否算作类型限定符或说明符?

c - glibc 从哪里获得它的 unicode 属性数据库?

c - char[n][100]是什么意思?

c - C11无锁乒乓球

mysql - 希望通过结合最大(或最小)对组进行一些澄清

python - Python 字典中的最大值

group-by - 在 Julia 中选择包含最小分组变量的 DataFrame 的行

linux - basic linux x86 assembly minimum number 返回不正确