c++ - 未初始化的变量读取错误

标签 c++ class variables

求一个数的数字和的程序。

编译后的代码报错:

runtime failure:variable 'z' is being used without being initialized.

如果我初始化'z',它不会删除z的原始值吗?

在此输入验证码

#include<iostream>

#include<cmath>
#include<string>
#include<iomanip>
using namespace std;
class sumd
{
int x;
  public:
void getdata()
{
    int z=0;
    cout<<"enter the no";
cin>>x;
z=x;
};
void sumdigit()
{
int z,y,sume,temp;             // this is the line with the error...
for(temp=z;temp>0;temp/=10)
{
    y=temp%10;
sume+=y;
}
cout<<sume;

};
};
  int main()
  {
  sumd s1;
   s1.getdata();
   s1.sumdigit();
   return 0;
      }

最佳答案

我认为问题是在这个方法中:

void sumdigit()
{
    int z,y,sume,temp;             // this is the line with the error...
    for(temp=z;temp>0;temp/=10)
    {
        y=temp%10;
        sume+=y;
    }
    cout<<sume;
}

您还没有为 zy 赋值;它们是未初始化的局部变量。我认为您可能打算使 zy 成为封闭类的数据成员。尝试将这些变量的定义移到该方法之外,看看是否能解决问题。

希望这对您有所帮助!

关于c++ - 未初始化的变量读取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9289112/

相关文章:

C++ 确定模板化变量是类还是内置类型?

python - 如何在Python中基于变量值创建字典

python - 根据时间相关变量不断变化的正弦音

c++ - 在 2 个不同的类上计算创建的对象会导致问题

c++ - 可变参数模板 initilizer_list 技巧

c++ - 需要 pow(-1,1.2) 为 1

PHP 错误 : mysql_num_rows(): supplied argument is not a valid MySQL

c++ - 定义一个类的不确定数量的实例

css - 将CSS类添加到多个元素

C - 将 argv 的值分配给变量