为什么不同的整数声明会改变结果?
Why does different integer declaration change the results?
问题存在于第一个嵌套循环中,结果没有按预期输出,我正在使用 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 2"
78 在第一行,其余在第二行。
预期结果:38 [当 "long long s[0] works well"]
结果:39 [当 "int s[0]" 给出此结果时]
如果我没有在代码中解释好,那就是问题所在:https://codeforces.com/contest/158/problem/B
数组大小应介于 1 到 100000 之间。根据用户输入创建数组。
do
{
cin >> n;
}
while (n < 1 || n > pow(10, 5));
虽然 运行 你的代码我在这段代码中遇到错误 long long s[n];
因为 n 应该是常量值。所以我更改了该代码。
解法:
long long* s = new long long(n);
创建数组后。您从用户那里获取输入来存储数组。该值介于 1 to 4
您检查的多重条件之间。
- 如果给定值为
4
,则 m++
和 s[i] = 0
或
- 在 else 部分给定值 + 数组元素检查该值是否等于 4 然后分配
s[i]
和 s[a] =0
问题存在于第一个嵌套循环中,结果没有按预期输出,我正在使用 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 2" 78 在第一行,其余在第二行。 预期结果:38 [当 "long long s[0] works well"] 结果:39 [当 "int s[0]" 给出此结果时] 如果我没有在代码中解释好,那就是问题所在:https://codeforces.com/contest/158/problem/B
数组大小应介于 1 到 100000 之间。根据用户输入创建数组。
do
{
cin >> n;
}
while (n < 1 || n > pow(10, 5));
虽然 运行 你的代码我在这段代码中遇到错误 long long s[n];
因为 n 应该是常量值。所以我更改了该代码。
解法:
long long* s = new long long(n);
创建数组后。您从用户那里获取输入来存储数组。该值介于 1 to 4
您检查的多重条件之间。
- 如果给定值为
4
,则m++
和s[i] = 0
或 - 在 else 部分给定值 + 数组元素检查该值是否等于 4 然后分配
s[i]
和s[a] =0