c - 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);
}
解决方案
正如帖子中已经提到的,当我第一次运行代码时,产品是一个负数,这让我相信发生了溢出。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);
}
推荐阅读
- postgresql - 尝试创建表忽略或未执行 postgresql
- mysql - 如果不存在则插入不插入
- regex - 要捕获的正则表达式:word {word} word
- docker - 在 docker 中运行两个服务节点和 python
- r - 使用 WSL 在 R 中运行 Linux 可执行文件
- firebase - 我可以信任提供给 functions.https.onCall 函数的用户信息吗?
- php - PHP构造函数不同格式
- r - 如何遍历字符向量的 R 列表以通过使所有字符保持在逗号后面并包括一个字符来修改每个元素
- android - Crashlytics 没有看到 NDK 套件
- wordpress - 如何为现有的 Woocommerce 产品文本字段添加占位符