C++ 在数组中查找最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7719978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:23:26  来源:igfitidea点击:

Finding max value in an array

c++

提问by classISover

int highNum = 0;
int m;
int list[4] = {10, 4, 7, 8};
    for (m = 0 ; m < size ; m++);
    {
        if (list[m] > highNum)
            highNum = list[m];
            cout << list[m];
    }
cout << highNum;

I am trying to find a simple loop to store a max value from an array, and I wrote this thinking it would work, but for some reason at the beginning of the for loop it stores the m variable as 4 and exits the loop. Can someone help me out?

我试图找到一个简单的循环来存储数组中的最大值,我写这篇文章认为它会起作用,但由于某种原因,在 for 循环开始时它将 m 变量存储为 4 并退出循环。有人可以帮我吗?

回答by Jerry Coffin

Unless you're doing this for homework and have to write the loop, just use std::max_element, as in:

除非您这样做是为了作业并且必须编写循环,否则只需使用std::max_element,如下所示:

int list[4] = {10, 4, 7, 8};
std::cout << *std::max_element(list, list+4);

...or better, avoid hard-coding the length:

...或者更好的是,避免对长度进行硬编码:

int list[] = {10, 4, 7, 8};
std::cout << *std::max_element(std::begin(list), std::end(list));

回答by kennytm

int highNum = 0;
int m;
int list[4] = {10, 4, 7, 8};
    for (m = 0 ; m < size ; m++);    // <-- semicolon?
    {
        if (list[m] > highNum)
            highNum = list[m];
            cout << list[m];
    }
cout << highNum;

Looking at your indentation, you may have missed a pair of {... }for the ifstatement as well.

看你的缩进,你可能已经错过了一对{...}if发言为好。

回答by Luke

You have a semicolon after your forstatement:

您的语句后有一个分号for

for (m = 0 ; m < size ; m++);
{

This should be:

这应该是:

for (m = 0 ; m < size ; m++)
{

回答by Ashutosh Narang

There is a ;right after the closing parentheses of your for loop: for (m = 0 ; m < size ; m++);

;for 循环的右括号之后有一个右边: for (m = 0 ; m < size ; m++);

The statements inside the block (inside the curly braces) gets executed only after the loop do nothingfor size number of times and that too only once.

块中的语句(花括号内)被执行只有在循环后做什么都不为次大小数和过一次。

You have also missed a pair of { ... }for the if statement as well.

您也错过了{ ... }if 语句的一对。

回答by Fezvez

You put a superfluous at the end ;in :

你把多余的放在最后;

for (m = 0 ; m < size ; m++);

Edit : Working code with some additional << endl;

编辑:带有一些附加功能的工作代码 << endl;

int size = 4;
int highNum = 0;
int m;
int list[4] = {10, 4, 7, 8};
for (m = 0 ; m < size ; m++)
{
    if (list[m] > highNum)
        highNum = list[m];
    cout << list[m] << endl;
}
cout << highNum << endl;