我正试着从一个网站上完成初学者的练习。
“需要:变量、数据类型和数值运算符--基本输入/输出逻辑(if语句、开关语句)循环(for,while,do-while)数组。
编写一个程序,要求用户输入10个不同的人( 1人、2人、.人、10人)早餐吃薄煎饼的数量,一旦输入数据,程序必须分析数据,并输出早餐吃的煎饼最多的人。“
我不知道怎样才能让节目叫出吃的煎饼最多的人?当然,这需要用键和值来完成,但是需求状态是“数组”,而不是“映射”?
下面是我想出的代码,但这只输出了最多吃的煎饼,所以没有真正回答这个问题!
非常感谢你的帮助!
*我只用了5个人来加速这个过程,然后我才知道怎么做*
#include <iostream>
using namespace std;
int main()
{
cout << "how many pancakes did you eat for breakfast?" << endl;
int person1, person2, person3, person4, person5;
cout << "Person 1: ";
cin >> person1;
cout << "Person 2: ";
cin >> person2;
cout << "Person 3: ";
cin >> person3;
cout << "Person 4: ";
cin >> person4;
cout << "Person 5: ";
cin >> person5;
int array[5] = {person1, person2, person3, person4, person5};
int temp = 0;
for (int i = 0; i<5; i++)
{
if (array[i] > temp)
{
temp = array[i];
}
}
cout << "The most pancakes eaten was " << temp << "by " << endl;
}发布于 2015-08-31 15:01:26
当然,这需要用键和值来完成。
这不是唯一的方法。另一种方法是使用没有键的索引集合,并假设位置k对应于可以单独从位置计算的键k。例如,如果您有一个与10人编号为1到10的10项对应的数组,那么person number k的数据可以存储在k-1位置的数组中。在这种情况下不需要键。
这个冗长的解释意味着,如果您在最佳i之外存储最好的tmp,那么在循环之后您将得到您的答案:
int temp = 0;
int res = -1;
for (int i = 0; i<5; i++) {
if (array[i] > temp) {
temp = array[i];
res = i;
}
}
cout << "The most pancakes eaten was " << temp << "by " << (res+1) << endl;注意,res+1是打印出来的,而不是res。这是因为数组是基于零的,而计数是基于一个的.
使用一个常用的成语,即使用初始元素作为当前最好的元素,并从1开始迭代,这可以进一步缩短。
int res = 0;
for (int i = 1 ; i<5 ; i++) {
if (array[i] > array[res]) {
res = i;
}
}
cout << "The most pancakes eaten was " << array[res] << "by " << (res+1) << endl;发布于 2015-08-31 15:10:46
如果你在输入时记录了吃薄煎饼的最大量,那该怎么办?
#include <iostream>
using namespace std;
// To execute C++, please define "int main()"
int main() {
int numPeople = 5;
int maxPancakes = -1;
int maxPerson = -1;
int currentPancakes = -1;
for (int i = 1; i < numPeople; i++) {
cout << "Person " << i << ": ";
cin >> currentPancakes;
if (currentPancakes > max) {
max = currentPancakes;
maxPerson = i;
}
}
cout << "Person " << maxPerson << " ate the most pancakes: " << maxPancakes;
return 0;
}注意:我的c++很生疏,我还没有测试过这个解决方案。(只是一个想法;)
发布于 2015-08-31 15:10:53
在这个问题上使用Map将是一个过分的问题。数组已经足够了。您甚至不需要遍历数组来检查谁吃得最多。获取最大值的操作实际上是O(0),因为我们可以在输入值时更新谁吃得最多。
int main(){
const int NUM_PEOPLE = 10;
int cakesEaten[10] = {0};
int maxEaten = 0;
int personId = 0;
cout << "How many pancakes eaten by:" << endl;
for(int x=0; x<NUM_PEOPLE; x++){
cout << "person " << (x+1) << ":";
cin >> cakesEaten[x];
if (cakesEaten[x] > maxEaten){
maxEaten = cakesEaten[x];
personId = x;
}
}
cout << "The most pancakes was eaten by person " << personID << endl;
}https://stackoverflow.com/questions/32314109
复制相似问题