发布整个代码(如果需要)
/* multiplication of n1 and n2*/
#include<stdio.h>
int arr[200]; //for storing the binary representation of n2
int k=0; // to keep the count of the no of digits in the binary representation
void bin(int n)
{
if(n>1)
bin(n/2);
arr[k++]=n%2;
}
int main()
{
int n1=1500000;
int n2=10000000;
int i=0,t=0;
long long int temp,pro=0;
bin(n2); // calculating the binary of n2 and stroring in 'arr'
for(i=k-1; i>=0 ;i--)
{
temp = (n1*arr[i]) << t; /* Why need cast here ? */
pro = pro + temp;
t++;
}
printf("product: %lld",pro);
return 0;
}
在上面的程序中,我没有得到想要的输出。但是当我这样做时:
temp = (n1*(long long int)arr[i]) << t;
,
然后我得到了正确的输出!
我无法理解上述行为?
最佳答案
在您的系统上,int
可能是 32 位,而 long long int
可能是 64 位。
n1
和arr[i]
都是int
,乘法结果就是int
。但是 int
中没有足够的位来保存答案,因为它太大了。
当您将操作的一个成员转换为 long long int
时,结果也将是 long long int
。
关于c - 为什么在下面的程序中需要cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545158/