简体   繁体   English

简单的C问题

[英]Simple C question

I was born in the modern world, so I don't often need to deal with this sort of thing, but could someone explain how to get the correct number in the following code. 我出生在现代世界,所以我不经常需要处理这类事情,但有人可以解释如何在以下代码中获得正确的数字。 Here is one attempt of many: 这是许多人的一次尝试:

#define     X   2527
#define     Y   2463
#define     Z   3072

main()
{
long int c = X*Y*Z;
printf("%ld",c);
}

I'm just trying to print a long integer but it is always printing the wrong result. 我只是想打印一个长整数,但它总是打印错误的结果。 Am I getting integer overflows - if so how can I prevent them? 我得到整数溢出 - 如果是这样我怎么能防止它们? Or is it my choice of printf formatter? 或者它是我选择的printf格式化程序?

Overflow is ok, because you trying 34 bit number write to 32 bit variable ( long int ). 溢出是可以的,因为您尝试将34位数写入32位变量( long int )。

Use long long int and %lld in format string. 在格式字符串中使用long long int%lld

#define     X   2527LL
#define     Y   2463LL
#define     Z   3072LL

main()
{
long long int c = X*Y*Z;
printf("%lld",c);
}

The problem is that the constants are not interpreted as long integers and the casting to long integer takes place only after the expression is calculated. 问题是常量不会被解释为长整数,并且只有在计算表达式后才会转换为长整数。 You can cast them in the expression to solve this or simply define them as long constants. 您可以在表达式中转换它们来解决这个问题,或者只是将它们定义为长常量。 Also, long may not be enough, long long should be used instead if it is supported. 此外,long可能还不够,如果支持long long应该使用long long。

Yes, you are getting overflow. 是的,你正在溢出。 The answer will not fit into 32 bit signed integer, which long int is. 答案将不适合32位有符号整数,long int为。 You have to use 64 bit type, that is long long. 你必须使用64位类型,这是很长的。

Also, you should do type casting, otherwise the intermediate calculation would overflow. 此外,您应该进行类型转换,否则中间计算会溢出。

#define     X   2527
#define     Y   2463
#define     Z   3072

main()
{
long long c = (long long)X*Y*Z;
printf("%lld",c);
}
#define     X   2527.0
#define     Y   2463
#define     Z   3072

main()
{
double c = X*Y*Z;
printf("%lf",c);
}

you can also use double. 你也可以使用双倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM