【问题标题】:Why does different integer declaration change the results?为什么不同的整数声明会改变结果?
【发布时间】: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


【解决方案1】:

数组大小应在 1 到 100000 之间。根据用户输入创建数组。

        do
        {
            cin >> n;
        } 
        while (n < 1 || n > pow(10, 5));

在运行您的代码时,我在此代码long long s[n]; 中遇到错误,因为 n 应该是 const 值。所以我改变了那个代码。

解决方案:

long long* s = new long long(n);

一旦创建了数组。您从用户那里获取输入来存储数组。该值介于 1 to 4 您的检查多个条件之间。

  1. 如果给定值为4,则m++s[i] = 0
  2. 在其他部分给定值+数组元素检查该值是否等于4然后分配s[i]s[a] =0

【讨论】:

  • 好像声明数组有问题,想问几个问题: 第一:我使用的codeblocks实际上避免了很多代码问题,有没有更好的推荐?第二:针对这个问题,我可以在哪个课题下多研究。第三:long long中的“新”是指什么?
  • 1.更好地使用视觉工作室。 2. C++中的数组声明和基本主题 3. new 是一个内存分配操作符。
猜你喜欢
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
  • 2020-11-23
  • 2010-09-20
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多