获取一个数组变量,其大小是用变量定义的,以进行赋值?

时间:2016-05-12 19:00:02

标签: c++ arrays

下面代码的目标是获取用户输入的变量(a和c),乘以它们(a * c),找到这个数字的因子,然后找出这些因素中的哪一个加起来为另一个用户输入的变量(在这种情况下,b)。由于某种原因,它没有正确编译,我不明白为什么。当我尝试使用命令cout << sum1 << endl << sum2 << endl;时,它会显示狂野的,不可预测的数字。任何人都可以告诉我我的代码是否有问题?这也是一个void函数,它将值sum1和sum2(在函数中创建)返回给main。变量a,b,c和f []都在main中定义。这是函数声明:

void findFactors(int, int, int, int[], int&, int&);

功能本身:

void findFactors(int a, int b, int c, int f[], int& sum1, int& sum2)
{   
    int j=0;
    int mult=a*c;
    int i, z=j, temp;

    for(i=1; i<=mult; i++)
    {
        if(mult%i==0)
        {
           f[j]=i;
           j++;
        }   
    }

    for(j=0; j>=0; j--)
    {
        temp=mult/f[j];
        if(temp+f[z]==b || temp-f[z]==b || f[z]-temp==b)
        {
           sum1 = f[z];
           sum2 = temp;
        }
    }
}

如果有人可以帮助我,我们将不胜感激。谢谢:))

1 个答案:

答案 0 :(得分:1)

void findFactors(int a, int b, int c, int f[], int& sum1, int& sum2)
{   
   int j=0;
   int mult=a*c;
   int i, z=j, temp; // here z == 0

   for(i = 1; i <= mult; i++)
   {
      if(mult % i == 0)
      {
         f[j] = i;   // Any # % 1 == 0, so f[0] = 1
         j++;        // note: z is still == 0 here
      }   
   }

   for(j = 0; j >= 0; j--)   // This loop executes only once
   {
      temp = mult / f[j]; // f[0] == 1, so temp == mult here
      // since z==0 here, f[0] == 1
      // so only if: b == (temp + 1) || (temp - 1) || (1 - temp) 
      if(temp + f[z] == b || temp - f[z] == b || f[z] - temp == b)
      {
         sum1 = f[z];   // z is still 0, so f[0] is 1, sum1 == 1
         sum2 = temp;   // temp == mult here, so sum2 == mult
      }
   }
} 

不确定此功能是否按预期运行,但除非满足变量b的条件,否则sum1sum2永远不会被设置,如果他们是,sum1应设为1sum2应为tempmult