首页 > 解决方案 > C Programming Help : 计算并打印从 1 到 30 的 3 的倍数的总和和乘积

问题描述

C Programming Help : 计算并打印从 1 到 30 的 3 的倍数的总和和乘积

请为此编程问题寻求帮助!我仍在学习 C 编程。欢迎任何提示和建议,非常感谢!

请帮助查看我编写的代码。

write a C program that calculates and prints the sum and product of the multiples of 3 from 1 to 30, as shown below
Sum is 165
Product is 214277011200*/

#include <stdio.h>
int main(void)

{
    int int1, sum, product;
    unsigned int i;

    sum = 0;
    product = 1;
    int1 =1;
    
    for (i = 1; i <= 30; i++) //mistake, after a for loop there should not be a ';' ...
    {
        if (i % 3 == 0) 
        {
            sum += i;
            product *= i;
            
        }
    }
    printf("Sum is %d\n", sum);
    printf("Product is %d", product);


}

标签: c

解决方案


正如帖子中已经提到的,当我第一次运行代码时,产品是一个负数,这让我相信发生了溢出。int 类型通常是 32 位,因此您必须使用 long 的 64 位类型。然后在 printf 字符串中 %d 用于 int 仍然会显示错误的值,因此您必须将其更改为 %ld 以获得 long int。像这样:

#include <stdio.h>
int main(void)

{
    long int1, sum, product;
    unsigned int i;

    sum = 0;
    product = 1;
    int1 =1;
    
    for (i = 1; i <= 30; i++) //mistake, after a for loop there should not be a ';' ...
    {
        if (i % 3 == 0) 
        {
            sum += i;
            product *= i;
            
        }
    }
    printf("Sum is %d\n", sum);
    printf("Product is %ld", product);


}

推荐阅读