求一个数的数字和的程序。
编译后的代码报错:
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;
}
您还没有为 z
或 y
赋值;它们是未初始化的局部变量。我认为您可能打算使 z
和 y
成为封闭类的数据成员。尝试将这些变量的定义移到该方法之外,看看是否能解决问题。
希望这对您有所帮助!
关于c++ - 未初始化的变量读取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9289112/