【问题标题】:Using arrays to determine the minimum [closed]使用数组确定最小值
【发布时间】:2014-08-11 21:30:43
【问题描述】:

为什么这个简单的代码不起作用? 一切似乎都很好,我没有收到任何错误(IDE:Visual Studio 2013) 有人可以帮忙吗?

int a[30];
int b;
int min = 0;

do {
    cin >> b;
    if (b != 0) {   
        int i = 0;
        a[i] = b;
        i++;
        if (min>a[i])
            min = a[i];
    }
} while (b != 0);

cout << endl << "THE MIN IS : "<<min<<endl;

【问题讨论】:

  • 为什么需要一个数组?您可以使用单个变量跟踪最小值。
  • 您在增加i 后错误地检查a[i]
  • 关于如何自己解决此类问题的一般提示:学习如何使用调试器。 codeproject.com/Articles/79508/…
  • 您没有收到错误,因为您有逻辑错误,而不是语法错误。如果您在第 31 个机会之前不输入 0 会发生什么?还要考虑如何在不将值存储在数组中的情况下做到这一点。
  • 在学习如何编程之前,您应该学习如何有效地提问。

标签: c++ visual-c++ c++11 visual-studio-2013


【解决方案1】:

程序具有未定义的行为,因为您使用了未初始化的数组元素。

在这段代码中sn -p

if (b != 0)
    {   
        int i = 0;
        a[i] = b;
        i++;
        if (min>a[i])
            min = a[i];

    }

您总是将 min 与未分配任何值的 a[1] 进行比较。在 if 语句的块语句中,变量 i 总是被重新创建并初始化为 0。然后它会增加,并将 min 与 a[1] 进行比较。但它只是分配了一个[0]。

事实上你不需要任何数组。代码可以这样写

bool empty = true;
int min;
int value;

while ( std::cin >> value && value != 0 )
{
   if ( empty || value < min )
   {
      empty = false;
      min = value;
   }
}

if ( !empty ) std::cout << "\nThe minimum is equal to " << min << std::endl;
else std::cout << "\nYou did not enter any number" << std::endl;

如果您需要将值存储在数组中,则代码如下所示

const size_t N = 30;
int a[N];
int value;

size_t i = 0;

while ( i < N && std::cin >> value && value != 0 ) a[i++] = value;

if ( i != 0 )
{
   int min = a[0];

   for ( size_t j = 1; j < i; j++ )
   {
      if ( a[j] < min ) min = a[j];
   }

   std::cout << "\nThe minimum is equal to " << min << std::endl;
}
else
{
    std::cout << "\nYou did not enter any number" << std::endl;
} 

考虑到在 C++ 的标头 &lt;algorithm&gt; 中声明了标准算法 std::min_element

【讨论】:

  • 我被要求将值存储在我的练习册中的一个数组中。不要怪我!!!在我错误地检查它之前,我一直在给 i 添加 1 个值。我有点粗心,也许不是一点点。
  • @Er Fun 查看我更新的帖子。
猜你喜欢
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 2020-05-17
  • 1970-01-01
  • 2021-07-11
  • 2013-02-25
相关资源
最近更新 更多