【问题标题】:Why is the output not right even tho im using 'long' data type here?为什么即使我在这里使用 \'long\' 数据类型,输出也不正确?
【发布时间】:2022-11-22 23:53:43
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    long x, y;
        
    printf("Enter the first number: \n");
    scanf("%ld", &x);
    
    printf("Enter the second number: \n");
    scanf("%ld", &y);
    
    long z = x + y;
    
    printf("The answer is: %ld \n", z);
    
    return 0;
}

我不能在这里添加超过 40 亿,尽管我应该在这里添加,因为我在这里使用“Long”数据类型。

enter image description here

【问题讨论】:

  • 在 Windows 上,longint 的宽度相同。在其他平台上 long 可能更大。您可以使用sizeof(int)sizeof(long) 进行检查。

标签: c


【解决方案1】:

由于long已签名,long可以取的最大值是2**31 - 1(<40亿)。

您可以改用 unsigned long,它可以取高达 2**32 - 1(> 40 亿)的值,或 long long/unsigned long long,它可以取更大的值。您还需要将相应的格式字符串更改为 %lu/%lld/%llu

【讨论】:

    【解决方案2】:

    long 的允许范围可能小至 [-2,147,483,647 ... +2,147,483,647]。当 long 是 32 位时,可能会发生这种情况。

    long 可能更宽,比如 64 位,然后处理范围 [-9,223,372,036,854,775,807 ... 9,223,372,036,854,775,807]。

    要确实处理 40 亿这样的值,请使用至少 64 位的 long long

    long long x, y;
    printf("Enter the first number: 
    ");
    scanf("%lld", &x);
    printf("Enter the second number: 
    ");
    scanf("%lld", &y);
    
    long long z = x + y;
    printf("The answer is: %lld 
    ", z);
    

    更细微的代码可能使用unsigned long来处理[0 ... 4,294,967,295]或int64_tint_least64_t...等类型

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 2019-08-19
      • 1970-01-01
      相关资源
      最近更新 更多