【问题标题】:Checking all values in an array [duplicate]检查数组中的所有值[重复]
【发布时间】:2017-10-24 22:33:18
【问题描述】:

我有一个这样的数字数组:

int array[5];

我正在尝试跳出 while 循环。我基本上想说如果数组中的所有数字都大于100然后结束循环。

有办法处理吗?

【问题讨论】:

标签: c++ arrays


【解决方案1】:

您可以检查数组中的每个元素,如果只有元素小于 100,则中断。

并且在循环之外根据i - 循环计数器 - 是否等于大小来打印消息。如果等于所有元素都更大,否则其中一个更小:

int array[] = {271, 120, 469, 77, 2000};
//int array[] = {271, 120, 469, 787, 2000}; // uncomment this line and comment out the line above to see the difference.


int i = 0; 
for(; i < 5; i++)
    if(100 > array[i])
        break;

if(i != 5)
    std::cout << "Not all the values are greater than 100" << std::endl;
else
    std::cout << "All the values are greater than 100" << std::endl;

【讨论】:

  • 由于这是 C++,在可能的情况下使用标准库仍然会更好,在这种情况下,来自 的 std::all_of 正如@user4581301 所建议的那样
猜你喜欢
  • 2015-04-12
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 2015-01-03
  • 1970-01-01
  • 2013-08-29
  • 2012-06-16
相关资源
最近更新 更多