My solution to chapter 6 exercise 9, not exactly right

33 views
Skip to first unread message

punstress

unread,
Sep 4, 2012, 2:13:37 AM9/4/12
to ppp-p...@googlegroups.com
I have a feeling I didn't do this in the way he intended, especially since I didn't need to use his hint. Mine will print out 123 is 0 thousands, etc, which doesn't comply with the instructions. How did/would you do it?

(Read 1-4 digits and print how many thousands, hundreds, etc. E.g., 123 is 1 hundred and 2 tens and 3 ones.)

int usernum = 0;
void analyze(int usernum);

int main() {
    cout << "Enter a number from 0 to 9999: ";
    cin >> usernum;
    analyze(usernum);
}
void analyze(int usernum) {
    int num2 = usernum;
   
    if (num2 < 0 || num2 > 9999) cerr << "Number out of bounds.\n";
    else {
    int thousands = num2 / 1000;
    if (thousands != 0) num2 -= thousands*1000;
    int hundreds = num2 / 100;
    if (hundreds != 0) num2 -= hundreds*100;
    int tens = num2 / 10;
    if (tens !=0) num2 -= tens*10;
    int ones = num2;
    cout << usernum << " equals " << thousands << " thousand(s), " 
        << hundreds << " hundred(s), " << tens << " ten(s),  and " << ones << " one(s).\n";
    }
    keep_window_open();
}
Reply all
Reply to author
Forward
0 new messages