0

I find myself stuck on credit. Can't figure out where the problem lies in my logic. Checksum gives 4 where it should give out 0. Ideas appreciated.


      //calculate checksum value

    int sum1, sum2, sum3, mod1, mod2, mod3, mod0 = 0;

    for(int i = 2; i <= 16 ;i += 2)
    {
        mod1 = (credit % (int) round(pow (10, i)))/ pow (10, i - 1);
        mod0 = mod1 * 2;
        mod2 = (mod0 % 10) + (mod0 / 10);
        sum1 = sum1 + mod2;
    }

    for (int i = 1; i <= 16; i += 2)
    {
        mod3 = (credit % (int) round(pow (10, i)))/ pow (10, i - 1);
        sum2 = sum2 + mod3;
    }
    sum3 = sum1 + sum2;
    int checksum = sum3 % 10;

2 Answers 2

0

Still pretty new to the CS50 course myself, but I am having a hard time understanding this line of code here; mod1 = (credit % (int) round(pow (10, i)))/ pow (10, i - 1);

Maybe the error might end up in there due to misplacement or omission of brackets? Another way is to create another variable that lets you break down the mathematical result of the variable mod1, so you can better look at your thought process.

1
  • Thanks for answering. However, the program compiles ok, yet gives a wrong answer. I learned that line from another answer here apparently because you have to convert the output of pow() to an int to use % Oct 15, 2021 at 14:42
0

Just in case someone runs into a similar problem, I figured out the primary problem myself after running debug50.

When typecasting pow(10,i) into an int, the program breaks down at 10 billion or pow(10,10) since, I presume, int can't hold that value. Typecasting instead with long pow(10,i) fixed the code and it runs correctly now. I guess it is important to remember to use long for credit.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .