未初始化的错误

Uninitialized Error

本文关键字:错误 初始化      更新时间:2023-10-16

我需要做什么来修复程序上的未初始化错误?该程序假设打印一个数字的除数数,但一直显示错误,指出变量 c 未初始化。

/*
/ Name: Ralph Lee Stone
/ Date: 10/10/2013
/ Project: RLStone3_HW_08
/ Description: This program gets a positive value and determines the number of divisors    it has.
*/
#include <iostream>
using namespace std;
int DivisorCount(int x)
{
  int counter = 0;
  for(int c; x < c; c++)
  {
    if (x%c==0)
     counter++;
  }
  return counter;
}
int main()
{
  int x;
  cout << "Please a positive value: ";
  cin >> x;
  cout << x << "has this many divsors: " << DivisorCount(x);
}

你需要用一些值初始化它:

for(int c = 1; x < c; c++)
//        ^^^ here

另外,你的意思是写c < x而不是x < c吗?

cfor 循环中有一个不确定的值:

for(int c; x < c; c++)
        ^

您需要将其初始化为一个值,例如:

for(int c=2; x < c; c++)

它需要大于 0也许是 2,因为您可能不希望 1 作为除数),因为您在此处的模运算中使用它:

if (x%c==0)

根据草案C++标准部分,0模量是未定义的行为 5.6 乘法运算符第 4 段说:

[...]如果/或 % 的第二个操作数为零,则行为未定义。[...]

看起来您可能已经翻转了结束条件,它应该从c < x而不是x < c

你没有给 c 任何初始值

for(int c; x < c; c++)

更改为

for(int c=0; x < c; c++) //assign a value

c初始化:

for(int c; x < c; c++)

这将声明(但不初始化)c,然后立即访问它以测试x < c是否 。

for(int c; x < c; c++) // what do you think is the value of c initially?
                       // and when do you think the loop will stop?

编辑我不知道你对未解决的外部错误是什么意思。如果我纠正你的错误

for(int c=1; c<x; c++) 

它编译并给出了合理的结果:5 有 1 个除数,9 有 2,8 有 3,12 有 5