【发布时间】:2019-09-24 04:59:22
【问题描述】:
问题存在于第一个嵌套循环中,结果未按预期输出,我正在使用 CodeBlocks 17.12
我尝试解决问题的方法是将“int s[n]”更改为“long long s[n]”,效果很好,但不幸的是,对于其他输入,我需要将其放回“int s[ 0]" 运行良好。
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n;
do
{
cin >> n;
}
while (n < 1 || n > pow(10, 5));
int s[n];
int m = 0;
//Inputs number of friends in each group.
for (int i = 0; i < n; i++)
{
do
{
cin >> s[i];
}
while (s[i] < 1 || s[i] > 4);
if (s[i] == 4)
{
m++;
s[i] = 0;
}
else
{
/* Hold each number of members in the groups and add them to the rest numbers to check if it would be equal to 4 then
if two numbers equal to 4, both numbers will be 0s. */
for (int a = 0; a < n; a++)
{
if (a != i)
{
if (s[i] + s[a] == 4)
{
m++;
s[i] = 0;
s[a] = 0;
}
}
}
}
}
cout << m << endl;
}
}
输入是“78 2 2 2 2 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 2 3 2 2 2 2 2 2 2 1 1 2 2 2 2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2" 第一行是 78,第二行是其余的。 预期结果:38 [当“long long s[0] 运行良好”] 结果:39 [当“int s[0]”给出这个结果时] 如果我没有在代码中解释清楚,那就是问题:https://codeforces.com/contest/158/problem/B
【问题讨论】:
-
请提供minimal reproducible example 并在问题本身中包含所有必要的信息,包括测试用例。
-
当您执行
idiv++时,您返回idiv,您将返回尚未递增的idiv的副本。为什么要进行后增量,但后增量在 if 语句之后立即被销毁?您还没有在整个代码中的任何地方使用它。您对我们的意思是预增量吗? -
@Onyambu 嘿,在主函数第 70 行的末尾附近,有这行 "m += roundtoP(z, 4);"实际上效果很好,我真的不明白你吗? “当您执行 idiv++ 时,您返回 idiv 您正在返回未递增的 idiv 副本”实际上它返回递增的值。
标签: c++ arrays loops variable-declaration