【问题标题】:Having Difficulty With This Q: Allow User To Input Values of Array and Do So With For, While loops, also output the largest number entered有这个问题的难点:允许用户输入数组的值,用for,while循环,也输出输入的最大数字
【发布时间】:2020-02-05 17:15:41
【问题描述】:

我必须创建一个使用 for 循环或 while 循环和数组的函数,以显示一组数字中的最大数字,但我遇到了标题中的问题。

当我运行此代码时,它不允许用户在数组中输入他想要的任意数量的元素,并且当用户想要通过输入 g 之类的字母来停止时它不会停止。它也不会在用户希望在数组中输入的内容的末尾输出最大的数字。

我的代码到底有什么问题?

   #include <iostream>
   using namespace std;

   void printarray(int array[], int size)
   {
for (int i = 0; i < size; i++)
{
    cout << array[i] << endl;
}

return;
   }

    int main()
    {
   const int SIZE = 2000;
   int count = 0;
   int userinput[SIZE];
   int largest = 0;


for (int i = 0; i < SIZE; i++)
{
    if (cin >> userinput[i])
    {
        count++;

    }   
    else
    {
        break;
    }

    while (count < userinput[i])
    {
        if (largest < userinput[i])
        {
            largest = userinput[i];
        }

        count++;                

                 }}

       printarray(userinput, count);

       cin.clear();
       cin.ignore();

       return 0;
          } 

【问题讨论】:

标签: c++ algorithm loops for-loop max


【解决方案1】:

代码的问题是它的缩进不好。

for (int i = 0; i < SIZE; i++)
{
    if (cin >> userinput[i])
    {
        count++;

    }   
    else
    {
        break;
    }

    while (count < userinput[i])
    {
        if (largest < userinput[i])
        {
            largest = userinput[i];
        }

        count++;                

                 }}

while 循环在 for 循环内。而while循环的这个条件

count < userinput[i]

没有意义。

分离循环。

for ( size_t i = 0; i < SIZE; i++ )
{
    if (cin >> userinput[i])
    {
        count++;

    }   
    else
    {
        break;
    }
}

int largest = count == 0 ? 0 : userinput[0];

for ( size_t i = 1; i < count; i++ )
{
     if ( largest < userinput[i] )
     {
         largest = userinput[i];
     }
}

考虑到您可以使用标头&lt;algorithm&gt; 中声明的标准算法std::max_element

例如

auto it = std::max_element( userinput, userinput + count );

if ( it != userinput + count ) largest = *it;

函数printarray可以这样声明和定义

std::ostream & printarray( const int array[], size_t size, std::ostream &os = std::cout )
{
    for ( size_t i = 0; i < size; i++ )
    {
        os << array[i] << ' ';
    }

    return os;
}

注意程序中没有输出最大元素的地方。

【讨论】:

    猜你喜欢
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2020-12-21
    • 2020-07-07
    相关资源
    最近更新 更多