简体   繁体   English

C++中的“while”命令

[英]"while" command in c++

In c++, I have to write a code to get the user's desired numbers in each line with "while" command and when the user enter number -1 at the end, I have to display the largest number, the largest number other than the previous number, and the number of row with the largest number entered.在c ++中,我必须编写一个代码来使用“while”命令在每一行中获取用户所需的数字,当用户在最后输入数字-1时,我必须显示最大的数字,除前一个之外的最大数字number,以及输入的最大数字的行数。 For example user's numbers is:例如用户的号码是:

4
7
11
5
-1

and result is:结果是:

11(the biggest number)
7(the biggest number after 11)
3(the row that the user has entered the largest number)

This is my own code:这是我自己的代码:

#include <iostream>

using namespace std;
int main()

{
int price;
int max=0;
cin>>price;
while(price!=-1)
{
    while(price>max)
    {   
    
    max=price;
    }

cin>>price;
}
cout<<max;
    return 0;   
}

I can find the largest number, but not the other two variables.我可以找到最大的数字,但不能找到其他两个变量。 Please reply ASAP.请尽快回复。

I don't want to spoon feed you the code.我不想用勺子喂你代码。 I will help you with the logic instead.我会帮你解决逻辑问题。

  1. Take input and store it in an array.获取输入并将其存储在数组中。
  2. Then use a sorting algorithm (there are tons of them, another opportunity for you to learn) to sort the array (or the vector)然后使用排序算法(有很多,你学习的另一个机会)对数组(或向量)进行排序
  3. Print the array打印数组

View the code only when you learn how to do it on your own:仅在您自己学习如何操作时查看代码:


std::vector<int> vec;
int input = 0;
while (input != -1) {
    std::cin >> input;
    vec.push_back(input);
}
std::sort(vec.begin(), vec.end());
for (auto& element : vec) {
    std::cout << element << " ";
}

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

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