Why am I getting a strange number in this code?

房东的猫 提交于 2021-02-05 12:07:53

问题


I want to write a C program that evaluates the factorials of the integers from 1 to 5 and print them in a tabular format. However, I keep getting a strange number over everything. Here's the code:

#include <stdio.h>

int main()
{
    int factorial;

    printf("X\t Factorial of X\n");

    for(int x=1; x<=5; x++)
    {
        factorial = 1;
        for (int j=1; j<=x; j++)
        {
            factorial *=j;
        }
        printf("%d\t %d\n", &x, &factorial);
    }

    return 0;
}

Here's the result of this code:

X        Factorial of X
6356768  6356772
6356768  6356772
6356768  6356772
6356768  6356772
6356768  6356772

What's wrong with my code? The result should be like this:

X       Factorial of X
1       1
2       2
3       6
4       24
5       120

回答1:


Remove & which stands for address of. You are printing address of the variable, not its value.

    printf("%d\t %d\n", x, factorial);



回答2:


When using printf (and related output functions), the %d format specifier expects an int as the corresponding argument. In your printf("%d\t %d\n", &x, &factorial); you are passing the addresses of the x and factorial variables.

So, just remove the two & (address of) operators: printf("%d\t %d\n", x, factorial);!

You are possibly being confused by the fact that, for scanf (and other input functions), the %d specifier requires a pointer to its target variable.




回答3:


printf("%d\t %d\n", &x, &factorial); &x and &factorial are addresses of those variables, not the variables themself. Omit the &.




回答4:


In the statement printf("%d\t %d\n", &x, &factorial); you have used '&' which prints the address of that element.




回答5:


Unlike scanf, printf() with format %d requires integer values, not addresses (&x is the address containing an integer, so a pointer to integer which type is int *). The correct expression is

printf("%d\t %d\n", x, factorial);

Why was the previous expression wrong?

With printf("%d\t %d\n", &x, &factorial); you are asking to printf to print the decimal representations of the addresses of x and factorial respectively.

For this reason it is not surprising that the values that used to be printed, 6356768 and 6356772:

  1. Are big numbers, multiples of 4 (because they address integers, that have a size 4 bytes, and in 32 bits architectures like yours are aligned to memory locations multiples of 4)
  2. They are memory locations, and their addresses do not vary even if their contents are changed

You can find printf documentation here.



来源:https://stackoverflow.com/questions/61460871/why-am-i-getting-a-strange-number-in-this-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!