Home > Software engineering >  Dividing a number in c by 3 long's
Dividing a number in c by 3 long's

Time:03-27

I'm currently writing a program where an user can input an amount that is dividable by the numbers 50, 20 and 10.

The way I'm trying to get it to work is that for example a user fills in the amount of 180, the program will calculate something like

"3 tickets of 50 have been used" "1 ticket of 20 has been used" "1 ticket of 10 has been used"

However, I have no idea where to even begin. I'm sorry if this is too vague but any help would be greatly appreciated

I tried to put my numbers into an array but that didn't work unfortunately. I also tried dividing them seperatly but that didn't work either

CodePudding user response:

What I believe you want is a divide and reduce schema:

#include <iostream>

int main() {
    std::cout << "enter amount: ";

    if(long ui; std::cin >> ui) {
        long c50s = ui / 50; // divide
        ui -= c50s * 50;     // reduce amount

        long c20s = ui / 20; // divide
        ui -= c20s * 20;     // reduce  amount

        long c10s = ui / 10; // divide
        ui -= c10s * 10;     // reduce amount

        std::cout
            << c50s << " tickets of 50 have been used\n"
            << c20s << " tickets of 20 have been used\n"
            << c10s << " tickets of 10 have been used\n"
            << "you have " << ui << " left\n"
        ;
    } else {
        std::cerr << "invalid input\n";
    }
}

Example if giving 180 as input:

3 tickets of 50 have been used
1 tickets of 20 have been used
1 tickets of 10 have been used
you have 0 left

If you do this a lot, you could create a helper function:

long div_and_reduce(long& input, long div) {
    long result = input / div; // divide
    input -= result * div;     // reduce
    return result;
}

int main() {
    std::cout << "enter amount: ";

    if(long ui; std::cin >> ui) {
        long c50s = div_and_reduce(ui, 50);
        long c20s = div_and_reduce(ui, 20);
        long c10s = div_and_reduce(ui, 10);
        // ...

CodePudding user response:

Any time you get stuck in programming, you should break the problem down. There are people who talk about "edit the null program until it does what it is suppose to." By this they mean start with nothing, and then address the first step (usually getting data into the program). Test it thoroughly. Then move onto the next step.

In your case, you need to collect data. So I would start with that. Start the program. Prompt the user and ask for the number they want. Just print it out. Make sure that works.

Then -- think about how you would do this manually. That will get you moving in the right direction for the next step. If that's too hard, then at least define the next step and break it down into pieces small enough you cna figure out how to do them, one step at a time.

Eventually the steps will be so small they are a line of code.

  • Related