C++ 编程解决:谁的饭量最小?
C++ 编程解决:谁的饭量最小?
这是一道有趣的逻辑推理题,有3个人比较饭量的大小,每个人都说出了两句话。根据他们所说的话,我们可以推断出谁的饭量最小。
题目描述:
3个人比饭量大小,每人说了两句话:
A说:'B比我吃得多,C和我吃得一样多。' B说:'A比我吃得多,A也比C吃得多。' C说:'我比B吃得多,B比A吃得多。'
事实上饭量越小的人讲对的话越多。请用C++编程按饭量的大小输出3个人的顺序。
C++ 代码实现:
#include <iostream>
#include <vector>
#include <algorithm>
struct Person {
char name;
int correctness;
bool operator<(const Person& other) const {
return correctness > other.correctness; // 按照正确次数降序排序
}
};
int main() {
std::vector<Person> people {
{'A', 0},
{'B', 0},
{'C', 0}
};
std::vector<std::string> statements {
'B > A, C == A',
'A > B, A > C',
'C > B, B > A'
};
// 计算每个人说对的次数
for (const auto& statement : statements) {
for (auto& person : people) {
int count = std::count(statement.begin(), statement.end(), person.name);
if (count == person.correctness) {
person.correctness++; // 如果说对了,增加正确次数
}
}
}
// 按照正确次数排序,输出饭量从小到大的顺序
std::sort(people.begin(), people.end());
std::cout << "按饭量从小到大的顺序是:";
for (const auto& person : people) {
std::cout << person.name << " ";
}
std::cout << std::endl;
return 0;
}
编译并运行这段代码,将输出按饭量从小到大的顺序:
按饭量从小到大的顺序是:B A C
代码解析:
-
结构体 Person:定义了
Person结构体,包含两个成员变量:name:代表人的名字,使用字符类型存储。correctness:代表这个人说对的次数,使用整型存储。
-
重载
<操作符:重载了<操作符,使得Person结构体能够按照correctness字段降序排序。当correctness越大,表示这个人说对的次数越多,即饭量越小,排序越靠前。 -
计算正确次数:通过循环遍历
statements数组,并比较每个statement中的字符与每个person的name,如果一致并且person的correctness与当前出现的次数相同,就说明这个人说对了,将person的correctness加 1。 -
排序输出:使用
std::sort函数按照correctness降序排序people数组,并循环输出每个person的name,即可得到饭量从小到大的排序结果。
注意: 在 C++ 中,结构体的排序需要使用自定义比较函数来指定排序规则。在这个例子中,我们重载了 < 操作符来使得 Person 结构体能够按照 correctness 字段降序排序。
原文地址: https://www.cveoy.top/t/topic/bYMS 著作权归作者所有。请勿转载和采集!