我正在努力学习C++(初级(。但我想知道如何在if
这样的语句中枚举变量。
我只是在变量之间加一个逗号吗?这个的正确语法是什么。。还是这一切都好?
#include <iostream>
using namespace std;
int main()
{
int a, b, c, d, e;
cin >> a >> b >> c >> d >> e;
if (a, b, c > e && a, b, c > d)
{
cout << a + b + c;
}
}
不,C++中没有这样的东西。你需要把每一个都分成自己的声明,比如:
if (a > e && b > e && c > e && a > d && b > d && c > d){
然而,这里的逻辑可以被简化。
如果您想要a > e
和a > d
,那么您只需要显示a
大于e
和d
中的较大者。a
、b
和c
的情况正好相反。换句话说,您只需要检查a
/b
/c
中最小的一个是否大于e
/d
中最大的一个。
所以这可以变成:
if (min({a, b, c}) > max(e, d)){
您不能在代码中执行您尝试过的操作。
显而易见的方法(初学者(已经在@scohe001的答案中显示出来了。然而,当你在某个时候学习模板和折叠表达式时,下面的解决方案会非常紧凑,与你尝试过的类似
#include <iostream>
#include <utility>
template<typename... Args>
constexpr bool all_of_greater(const int lhs, Args&&... rhsArgs)
{
return ((lhs < std::forward<Args>(rhsArgs)) && ...);
}
现在你可以做类似于你在代码中所做的事情:
if (all_of_greater(e, a, b, c) && all_of_greater(d, a, b, c))
{
std::cout << a + b + c;
}
(请参阅在线演示(
这里有一个重新设计的方法;值";以及";目标";分为两个独立的vector
结构以便于比较:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
// Helper function to read an arbitrary number of entries into a vector
void read_n(std::vector<int>& list, const size_t n) {
for (size_t i = 0; i < n; ++i) {
int v;
std::cin >> v;
list.push_back(v);
}
}
int main() {
// Container to hold the values
std::vector<int> values;
read_n(values, 3);
// Container to hold the targets
std::vector<int> targets;
read_n(targets, 2);
// Ensure that for each target...
for (auto target : targets) {
// ...all of the values exceed that target...
if (!std::all_of(values.cbegin(), values.cend(), [target](int i) { return i > target; })) {
// ...or else it's a fail.
return -1;
}
}
// Use accumulate to compute the sum and display it.
std::cout << std::accumulate(values.cbegin(), values.cend(), 0) << std::endl;
return 0;
}
在编写代码时,请尝试根据结构和循环进行思考,而不仅仅是复制粘贴代码以添加更多变量。