سؤال

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top