【问题标题】:maximum and minimum - sentinel controlled repetition [closed]最大和最小 - 哨兵控制重复[关闭]
【发布时间】:2012-10-26 19:31:32
【问题描述】:

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

“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;
}

【问题讨论】:

  • 你应该初始化局部变量。
  • 输入数字(-1 退出):44 输入数字(-1 退出):32 输入数字(-1 退出):2 输入数字(-1 退出) :-1 数字无效 最小值=2 最大值=2674276(最大值不起作用)。 ://
  • @Marc 它正在工作。我设置了 max = 0。为什么我不需要初始化“min”?
  • 一秒,我正在写我的答案如何设置最小值和最大值
  • @Nomics 我的答案已更新

标签: c max minimum sentinel


【解决方案1】:

未初始化变量的值为 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 );

【讨论】:

  • 您在赋值之前使用的所有这些。这是最小值和最大值,但不是数字。
  • 最好初始化int max = INT_MIN; int min = INT_MAX;,这样如果用户只输入数字&gt; min&lt; max,您就不会感到厌烦。
  • 好点,这是另一种方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 2014-10-19
  • 1970-01-01
  • 1970-01-01
  • 2013-11-11
  • 1970-01-01
相关资源
最近更新 更多