简体   繁体   中英

Why does this program loop forever?

The goal of the program is to perform a checksum in the following way: multiply every other digit by 2, starting with the number's second-to-last digit, and then add those products' digits together. Add the sum to the sum of the digits that weren't multiplied by 2. If the total modulo 10 is 0, the number is valid The problem with my code is that it runs forever, therefore I suppose something is wrong with the loops, any suggestion on why that might be happening and how to fix it? Note:

#include <stdio.h>
#include <cs50.h>
#include <math.h>

double input(void);

int main(void)
{
    double number = input();
    double sum = 0;
    double i = 1;
    double current_digit;
    do
    {
        current_digit = (fmod(number, pow(10,i)) - fmod(number, pow(10, i-1)))/pow(10, i-1); //formula to calculate the ith digit in a number
        if (fmod(i,2) != 0)
        {
            sum += current_digit;
        }
        else
        {
            double second_number = 2*current_digit;
            double j = 1;
            do
            {
                double second_current_digit = (fmod(second_number, pow(10,j)) -fmod(second_number,pow(10, j-1)))/pow(10, j-1);
                sum += second_current_digit;
                j++;
            }
            while (fmod(second_number, pow(10,j)) == number);
        i++;
        }
    }
    while (fmod(number,pow(10, i)) != number);
    if (fmod(sum,10) == 0)
    {
        printf("true");
    }
    else
    {
        printf("false");
    }
}

double input(void)
{
    double number = get_double("Number: ");
    return number;
}

the usage of double... the program will have to take in 16 digits or even more, I didn't know what to do to handle larger integers, maybe long type?

Most computers these days support 64-bit integers natively. Those can give you as many as floor(log_10(2^64)) = 19 decimal digits. If that's sufficient, use uint64_t from <stdint.h> (it's a type defined in the C standard).

If that's not sufficient, consider using an array of digits, or a more involved "big integer" data type, as in here .

Anyway, I'm betting the exact floating-point comparison is what's biting you, as, probably, the value of pow(10,i) is not an exact power of 10, so the fmod() changes number slightly. But - don't trust my guess, just use a debugger:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM