c - 编写一个程序求正奇数之和与小于或等于30的正偶数的乘积

标签 c types int

我在为这个问题编写 C 程序时遇到了一些问题。也许我读错了问题并以错误的方式做。有人可以帮我吗?这就是我尝试做的方式

#include<stdio.h>
void main(void)
{
    int j, sum=0;
    long int product=1;
    for(j=1;j<=30;j=j+2)
    {
        sum=sum+j;
    }
    for(j=2;j<=30;j=j+2)
    {
        product=product*j;
    }
    printf("\nThe sum of positive odd numbers is: %d", sum);
    printf("\nThe product of positive even numbers is: %d", product);
}

我得到的输出是:

The sum of positive odd numbers is: 225
The product of positive even numbers is: -1409286144

我弄错了产品部分。我试过使用 unsigned long int、long long、unsigned long long。什么都没用。

最佳答案

尝试在 printf 中使用 %ld 而不是 %d:

printf("\n正偶数的乘积是:%ld", product);

因为它是 long int 而不是 int

如果您使用long long int,您需要%lld。考虑到这是一个非常非常大的产品,您可能需要长尺寸。我不知道你的平台的 long int 是 32 位还是 64 位,但你肯定需要一个 64 位的数字。

long long 格式字符串可能会根据您的具体平台和编译器而有所不同,但如今大多数事情都已在 %lld 上标准化。特别是,旧的 Microsoft 编译器有时使用 %I64d

关于c - 编写一个程序求正奇数之和与小于或等于30的正偶数的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16310326/

相关文章:

c# - Main 是一个 'type' 但像 'variable' 一样使用

typescript - `any[never]` 是 `any` 类型是否正确?

c - 披萨代码不起作用 | Cinnamon 上的 C 编程

将 2 个 char 转换为 1 个 int

右移运算符对符号类型的编译器依赖性 :

c - 访问 PCIe 设备的内部寄存器

scala - 使用抽象类型而不是参数类型的 F-Bound 多态性?

swift - 如何屏蔽 Swift 中的最后一个数字?

c - C中的全局变量是自动变量吗?

c程序不等待输入