为什么我在此代码中得到一个奇怪的数字? [英] Why am I getting a strange number in this code?

查看:51
本文介绍了为什么我在此代码中得到一个奇怪的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个C程序,该程序对从1到5的整数的阶乘进行求值,并以表格格式打印它们.但是,我在所有事情上都得到一个奇怪的数字.这是代码:

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;
}

这是此代码的结果:

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

推荐答案

删除代表地址的& .您正在打印变量的地址,而不是其值.

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

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

这篇关于为什么我在此代码中得到一个奇怪的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆