我想要计算我的邮政编码中每个数字的总和,所以我写了这样的实现函数但是,它显示“0”作为答案,然后我意识到应该先调用,我将correctionDigitOf()添加到构造函数“Zipcode :: Zipcode“然后我的邮政编码全部为”0“,所以请帮忙!
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <cmath>
using namespace std;
class Zipcode
{
public:
Zipcode();
void createZipcode();
int getZipcode();
int extract(int location);
int getCoreectionDigit();
void correctionDigitOf();
private:
int zipcode;
int correctionDigit;
};
Zipcode::Zipcode()
{
zipcode = 0;
correctionDigit = 0;
createZipcode();
}
void Zipcode::createZipcode()
{
zipcode = 10000 + rand() % 99999;
}
int Zipcode::getZipcode()
{
return zipcode;
}
int Zipcode::extract(int location)
{
int i = 1;
while (i<location)
{
i++;
zipcode /= 10;
}
return zipcode % 10;
}
void Zipcode::correctionDigitOf()
{
correctionDigit = extract(1) + extract(2) + extract(3) + extract(4) + extract(5);
}
int Zipcode::getCoreectionDigit()
{
return correctionDigit;
}
int main()
{
const int num = 10;
for (int i = 0; i<num; i++)
{
Zipcode zip;
cout << zip.getZipcode()
<< ' '
<< zip.getCoreectionDigit()
<< endl;
}
return 0;
}
答案 0 :(得分:0)
您的Zipcode::extract
更改了zipcode
的值,这可能是您想要的。