计算我的邮政编码中的数字总和

calculate sum of digit in my zip code

本文关键字:数字 我的 邮政编码 计算      更新时间:2023-10-16

我想计算邮政编码中每个数字的总和,所以我写了这样的实现函数,但是,它显示"0"作为答案,然后我意识到它应该首先调用,我将correctionDigitOf()添加到构造函数"邮政编码::邮政编码"中,然后我的邮政编码在我这样做后都是"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;
}

你的Zipcode::extract会改变zipcode的值,这不可能是你想要的。

相关文章: