简体   繁体   中英

Why does my program compile but not do anything?

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

int * get_digs(long card, int digs, int idigs[]);

int main()
{
    long card = get_long("Number: ");
    int digs = ceil(log10(card));
    int idigs[digs];

    get_digs(card, digs, &idigs[digs]);

    for(int k = 0; k == digs; k++) // This loop is to check if the program is doing what I'm 
    {                              // asking it to do.
        printf("%i", idigs[k]);
    }
}

int * get_digs(long cd, int dg, int idg[])
{
    int j = dg;
    int dig = 0;

    for(int i = 0; i == dg; i++)
    {
        dig = floor(cd / pow(10, j));
        j--;
        idg[i] = dig % 10;
    }
    return 0;
}


This program is supposed to take an input from the user, let's say a credit card, get its digits and store them on an array. The program compiles, but it doesn't even print the for loop on the main function... It just asks for input. What am I doing wrong?

The second expression in a for loop's control block is a condition for iterating, not for breaking from the loop. Thus, this for loop...

 for(int k = 0; k == digs; k++)

... executes the loop body only if k is equal to digs , and that will be true the first time the condition is checked only if digs is zero, which you (reasonably) do not expect to be the case. Furthermore, unless k were also modified inside the loop body, which it isn't in your code, the body would never execute more than once. It's similar in effect, then, to if (k == digs) , and of course the loop body is not executed even once.

The standard idiom for what you are trying to do uses a < expression in the condition:

    for (int k = 0; k < digs; k++)

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