简体   繁体   中英

Why can't my C program complete the code after inputing a number?

I just started learning C so I have no idea why this is happening.

#include <stdio.h>

int square(int x);

int main(int argc, const char * argv[])
{
    printf("Enter a number");
    int userNum;
    scanf("%d", &userNum);
    int result = square(userNum);
    printf("The result is %d", result);

}

int square(int x){
    int result = x*x;
    return result;
}

It would ask for a number but then nothing would happen after I input. If I were to take the scanf out and put square(10) or something, the code will run and finish.

It compiles and runs as expected for me using both gcc and clang ... to make it more clear (as maybe other text is getting in your way of seeing the answer) add new lines to what you are outputting to stdout :

int main( void ) {
    printf("Enter a number: ");

    int userNum;

    scanf("%d", &userNum);

    int result = square(userNum);

    printf("\nThe result is: %d\n", result);

    return 0;
}

If you are testing in terminal (and not piping input) then recall that scanf (with the %d placeholder) will read an integer until the next character that is not a numerical character. So on your keyboard you will need to type 10 and return (or enter). Otherwise, pipe your program an input file:

10

... using the following command:

./a.out < input.txt

Your main function says that the return type is " int " , but you are not returning any value.

Just add a statement return 0 at just before the last closing braces of the main function.

It should work fine. Here is the same program and it works fine.

http://ideone.com/H3Izqh

#include <stdio.h>

int square(int x);

int main(int argc, const char * argv[])
{
    printf("Enter a number");
    int userNum;
    scanf("%d", &userNum);
    int result = square(userNum);
    printf("\nThe result is %d", result);
    return 0;   //NOTICE THIS STATEMENT
}

int square(int x){
    int result = x*x;
    return result;
}

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