c - 为什么在下面的程序中需要cast?

标签 c casting

发布整个代码(如果需要)

 /* 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 位。

n1arr[i]都是int,乘法结果就是int。但是 int 中没有足够的位来保存答案,因为它太大了。

当您将操作的一个成员转换为 long long int 时,结果也将是 long long int

关于c - 为什么在下面的程序中需要cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545158/

相关文章:

c - libpcap 丢弃来自特定 IP 的一些数据包

arrays - 如何将 byte slice 段 (&[u8]) 的缓冲区转换为整数?

C# - 转换为基本类型如何工作?

c - 删除 R/C 中的字节顺序标记

c# - 如何从对象列表中获取特定类型的对象

java - 如何强制面板访问类方法以返回对象?

c - 未初始化指针的可能输出

c - C中的格式化耗时

c - '->' 的类型参数无效

c - 如何将char数组的内容读写到文件中?