c++ - 检查我们是否可以用数字求奇数的程序
问题描述
所以基本上这个程序需要几个测试用例,这些测试用例由一系列数字(长度为 n)组成。应该看到,如果序列中至少存在一个长度为 x 的组合,那么它们的总和将是奇数。仅存在一种这样的组合就足够了。如果可能,我们打印“是”,否则打印“否”。
例如,如果我们输入 1(t=1,一个测试用例)3 2(n=3,也就是总共 3 个 nrs,x=2,也就是考虑其中任意 2 个)16 11 12(这些是数字)
2个偶数,1个奇数。11+12 是奇数,所以输出是 Yes。
我的问题是这种情况特别
3 3
101 102 103
如果我自己检查它,这意味着只有这一个测试用例,它会输出正确的“否”。如果它与其他测试用例一起,意味着它是测试 2 或更低,它输出“是”。
谁能告诉我为什么?我真的很感激。
这是代码。
#include <iostream>
using namespace std;
int main()
{
int t, n, x, k, c_even{ 0 }, c_odd{ 0 };
string v{"No\n"};
cin >> t;
//t is the number of total cases
for (int i = 1; i <= t; i++)
{
c_even = 0; //counter for even numbers
c_odd = 0; // counter for odd numbers
cin >> n >> x; // n is the total length of the sequence of nrs, x is how many numbers we consider out of the sequence
//this for loop is for introducing the sequence and counting how many nrs are odd and even
for (int j = 1; j <= n; j++)
{
cin >> k;
if (k % 2 == 0)
c_even++;
else c_odd++;
}
//obv if there are no odd nrs, sum won't ever be odd
if (c_odd == 0)
v = "No\n";
/*
for example, say we have 5 odd numbers, 3 even, and we have to consider 5 numbers out of total 8.
the for loop starts with 1. it checks if 1+3>=5, meaning if we have enough even nrs to make odd sum. it's not correct in this case.
then it goes to o=3; it checks if 3+3>=5. correct! so we have enough even nrs to make odd sum. other cases don't have to be considered.
*/
else for (int o = 1; o <= c_odd; o += 2)
{
if (o + c_even >=x)
{
v = "Yes\n";
break;
}
}
cout << v;
}
}
解决方案
只好先搬进string v{"No\n"};
去了。
正如cigien所说,如果string v{"No\n"};
在第一个循环之外,如果一个迭代将 v 设置为“是”并且下一个不满足
if (c_odd == 0)
v = "No\n";
换句话说,v 保持“是”,程序会自动输出“是”,尽管它不是正确答案。
通过将那段代码移动到第一个 for 中,我们确保每次迭代都以 v 作为“否”开始。
推荐阅读
- java - 使用 Java 中的 Solrj 连接到 Solr 时出错
- python-3.x - 检查数据框中的行是否大致对应
- python - 如何将 OpenCV 阈值方法应用于 Skimage 方法输出的形态图像?
- javascript - 如何使用 jQuery 或任何其他方式添加结束标记
- inheritance - JHipster 继承
- api - 带有 Google Identity OAuth 2.0 令牌的 Firestore 的 REST API
- sql - 使用 sql 返回多列:错误查询没有结果数据的目的地
- jquery - 触发点击事件到数据表中的隐藏行
- html - 为什么我的盒子没有弯曲到容器的末端?
- mysql - “无法加载身份验证插件'caching_sha2_password'”在使用 mysql 部署 docker 时