数组和 For 循环:创建从大到小的数字列表
Arrays and For Loops: Creating a list of numbers Greatest to Least
#include <iostream>
using namespace std;
int main() {
int greatestToLeastPancakeAmount[10] = {};
int greatestToLeastPersonNumber[10] = {};
int pancakeAmount;
int x;
cout << "Pancake Glutton 1.0 nn"; //State program's title
cout << "10 Different people ate pancakes for breakfast.. nn";
x = 0;
for(x=0;x<10;x++) {
cout << "How many pancakes did person " << (x + 1) << " eat? > ";
cin >> pancakeAmount;
greatestToLeastPersonNumber[x] = (x + 1);
greatestToLeastPancakeAmount[x] = pancakeAmount;
/*while(pancakeAmount > greatestToLeastPancakeAmount[(x - 1)]) {
int storeGreatestToLeastPancakeAmount = greatestToLeastPancakeAmount[(x-1)];
int storeGreatestToLeastPersonNumber = greatestToLeastPersonNumber[(x-1)];
greatestToLeastPancakeAmount[(x-1)] = pancakeAmount;
greatestToLeastPersonNumber[(x-1)] = x;
greatestToLeastPancakeAmount[x] = storeGreatestToLeastPancakeAmount;
greatestToLeastPersonNumber[x] = storeGreatestToLeastPersonNumber;
}*/
}
cout << "nn";
for(x=0;x<10;x++) {
cout << "Person " << greatestToLeastPersonNumber[x] << " ate " << greatestToLeastPancakeAmount[x] << " pancakes!n";
}
return 0;
}
我如何输出吃煎饼最多的人数,其次是煎饼量最少的人?
让我们从一般要求开始: 阅读后,您始终需要验证您是否成功阅读了您尝试阅读的任何内容,例如:
if (!(std::cin >> greatestToLeastPancakeAmount[x])) {
std::cout << "failed to read number of pancakes (ignoring this line)n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
接下来,实际上不需要为人员存储任何标识符:
- 不需要。
- 存储的标识符始终
i + 1
i
无论如何都是索引。
使用您的设置,计算吃最多或最少煎饼的人数的最简单方法可能是std::sort()
数组,然后在数组的开头和结尾计算相等计数的数量。然而,一种更简单的方法是,在std::map<int, int>
中增加一个值,然后输出映射的第一个和最后一个元素:
std::map<int, int> count;
for (int i = 0; i != 10; ++i) {
++count[greatestToLeastPancakeAmount[i]];
}
if (count.empty()) { // won't happen until you start tracking the number of people entered
std::cout << "nobody ate any pancaken";
}
else {
std::cout << (--count.end())->second << " persons ate " << (--count.end())->first
<< " pancakesn";
std::cout << count.begin()->second << " persons ate " << count.begin()->first
<< " pancakesn";
}
相关文章:
- 为什么在浮点中从大到小会引入更多的误差
- 通过 Rcpp 和 bit64 R 包将最大的int64_t变量值从 C++ 传递到 R
- 如何将较大数字中从0到9的单个数字放入只包含数字的数组中
- QT-如何通过按下按钮从子窗口小部件返回到父窗口小部件
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 在获取从文件到矢量的每一行之后,数字将被更改或销毁
- 使用从1到N的数字初始化std数组模板参数
- 如何编写一个递归函数,以随机的方式混淆从0到6的数字
- 如何使用递归计算从 0 到给定数字的奇数?
- 从大范围内生成一个随机数,但从大范围的中间开始生成较小的范围
- 从C 到C#调用INT []显示随机大数字,而不是原始数组成员
- 如何从大到小组织数组中的前 10 个常用值
- C 如何从向量到给定数字的向量中找到最小元素数量
- 在 c++ 中从字符串到 int 的大数字
- 排序类对象数据成员从大到小
- 数组和 For 循环:创建从大到小的数字列表
- C++数组从最大到最小的数字
- C++从1到非常大的数字(例如2500万)的随机数
- 如何移动数组中的元素,将奇数放到数组的开头(从最小到最大),甚至放到后面(从最大到最小)
- 使用Std::vector::reserve时,Std::sort顺序从大到小