繁体   English   中英

如何显示数组中的最大值?

[英]how to display the maximum value in the array?

int main()
{
   int numbers[30];
   int i;

   // making array of 30 random numbers under 100
   for(i=0;i<30;i++)
   {
       numbers[i] = rand() % 100; 
   }

   // finding the greatest number in the array
   int greatest = 0;
   srand(1);
   for(i=0;i<30;i++)
   {
        if ( numbers[i] > greatest) 
            greatest = numbers[i];
   }

然后如何告诉程序显示数组的最大值? 谢谢

要将其显示在基本控制台输出中:

#include <iostream>
...
std::cout << "Max value is: " << greatest << "\n";
#include <iostream>

std::cout << greatest << '\n';

在旁注中,您可能想在调用rand()之前先调用srand() rand() (并且可能想提供一个更有意义的参数)。

如果您不打算这样做,我建议您使用std :: max_element(在<algorithm>可用)。

std::cout << "Max Value: " << *(std::max_element(number, numbers+30)) << std::endl;

否则,程序中剩下要做的就是打印该值。 您可以使用std :: cout(在<iostream>可用)。 计算完for循环中的值之后。

// Dump the value greatest to standard output
std::cout << "Max value: " << greatest << std::endl;

这就是您的意思吗?

printf("%d", greatest);

确保包括“ cstdio”。

std::cout << greatest <<endl;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM