0

I'm working on credit.c in pset1, and I've decided to implement a "get length" method that I'm testing. I think my logic is sound, but I'm getting an infinite loop when running the following code:

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

int main(void)
{
    long long cnum = 378282246310005;
    long long length = 0;

    for(long long i = 0; (((10^i)-cnum) < 0); i++)
    {
        length = i;
    }

    printf("%lli\n", length);
}

The logic goes that, at 15 loops, 10^14-378282246310005 is negative, and 10^15-378282246310005 is positive. So it should exit the loop when i is 15, but it's instead looping infinitely. Any idea why that might be?

1 Answer 1

1

The ^ operator is the Bitwise XOR operator in C as well as many languages that derive their syntax from C (including C++, Python and Java).

I assume you want the power operator. There is no power operator in C, so you need to use a function (and #include <math.h>). There IS a power operator in some languages (like Python: x**y). This would be the replacement line of code:

for(long long i = 0; pow(10, i) - cnum < 0; i++) {

When you are debugging your program, don't forget to TEST your assumptions. If you have an infinite loop, try adding printf statements to see what values the computer is actually computing.

If you run this loop:

for (long long i = 0; i <= 15; i++) {
    printf("10^%lld=%lld\n", i, 10^i);
}

You will get the results:

10^0 = 10
10^1 = 11
...
10^14 = 4
10^15 = 5

The bitwise XOR operator creates a new value by performing a logical XOR operation on the corresponding binary bits of the two values.

You must log in to answer this question.

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