未初始化的错误
Uninitialized Error
我需要做什么来修复程序上的未初始化错误?该程序假设打印一个数字的除数数,但一直显示错误,指出变量 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
吗?
c 在 for 循环中有一个不确定的值:
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
相关文章:
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 如何使用C++初始化向量;脚本化值不是数组、指针或矢量错误
- 分段错误 - 读取初始化指针的数组
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 修复未初始化的局部变量错误
- 初始化迭代器错误 C++ 在 GCC 编译器中
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 类型为 "Bucket&"(未限定的 const 限定)的引用不能使用 "SortedList." 类型的值进行初始化 如何修复此错误?
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么我在向量初始化时收到此错误?
- C1001内部编译器错误是由于矢量初始化(如数组)引起的
- 初始化thread_local叮当中的错误
- Eclipse:错误:初始化模式失败(无法连接到目标)
- C 错误:初始化量太多
- Seg 错误初始化列表向量与控制台输入
- 通过传递的指针段错误初始化 char 数组
- c++错误:初始化器元素不是常量
- C++错误:初始化结构实例的向量数组成员
- Visual Studio C++11g编译错误-初始化程序过多
- OpenCV 错误:初始化 OpenCLDevices 中的 GPU API 调用 (-1001)