C语言while循环编程练习:3和4的倍数判断问题咨询
编程练习问题与代码修正
练习需求
编写一个程序,接受N个偶数作为输入,并输出:
- 输入的数字总数
- 3的倍数的平均值
- 4的倍数的乘积
- 负数的乘积
程序只能使用while循环结构。
用户编写的原始代码
#include <stdio.h> #include <stdlib.h> int main(void) { int i, N, P=0, M=0, T=1, X=-1; printf("Enter ending value: \n"); scanf("%d", &N); while (P<=N){ if(i%2==0){ scanf ("%d", &i); P= P + 1; if(i%3==0){ M = M + i; } if (i%4==0){ T = T * i ; } if (i < 0){ X = X * i; } M = M / 2; } } printf ("The sum of the numbers is %d \n", P); printf ("The average of multiples of 3 is: %d \n", M); printf ("The product of multiples of 4 is: %d \n", T); printf ("The product of negative numbers is: %d \n", X); return 0; }
问题解答
1. 判断同时被3和4整除的条件
直接用逻辑与运算符结合模运算即可,两种等价写法:
- 写法1:
if (i % 3 == 0 && i % 4 == 0) - 写法2:
if (i % 12 == 0)(3和4互质,最小公倍数为12)
2. 3、4倍数的代码实现
你提到的数学规则是正确的,但代码中直接用模运算%更简洁高效,无需手动实现规则:
- 判断3的倍数:
i % 3 == 0 - 判断4的倍数:
i % 4 == 0
如果非要按你说的规则手动实现(仅作学习参考,实际开发不推荐):
手动实现3的倍数判断
int sum = 0; int temp = i; // 处理负数,取绝对值 if (temp < 0) temp = -temp; while (temp > 0) { sum += temp % 10; temp /= 10; } if (sum % 3 == 0) { // 是3的倍数 }
手动实现4的倍数判断
int last_two = abs(i) % 100; // 取最后两位,处理负数 if (last_two % 4 == 0) { // 是4的倍数 }
原代码的bug修正与优化
你的代码存在多处逻辑错误,以下是修正后的版本:
#include <stdio.h> int main(void) { int input_num, N, count = 0; int sum_multi3 = 0, count_multi3 = 0; long long product_multi4 = 1; // 用long long避免整数溢出 long long product_negative = 1; int has_multi4 = 0, has_negative = 0; printf("Enter the number of even integers to input: "); scanf("%d", &N); // 循环输入N个有效偶数 while (count < N) { printf("Enter even integer %d: ", count + 1); scanf("%d", &input_num); // 过滤非偶数,要求重新输入 if (input_num % 2 != 0) { printf("Please enter an even number!\n"); continue; } count++; // 统计3的倍数的总和与数量 if (input_num % 3 == 0) { sum_multi3 += input_num; count_multi3++; } // 统计4的倍数的乘积 if (input_num % 4 == 0) { product_multi4 *= input_num; has_multi4 = 1; } // 统计负数的乘积 if (input_num < 0) { product_negative *= input_num; has_negative = 1; } } // 输出结果 printf("\n--- Results ---\n"); printf("Total numbers input: %d\n", count); if (count_multi3 > 0) { printf("Average of multiples of 3: %.2f\n", (double)sum_multi3 / count_multi3); } else { printf("Average of multiples of 3: No multiples of 3 found\n"); } if (has_multi4) { printf("Product of multiples of 4: %lld\n", product_multi4); } else { printf("Product of multiples of 4: No multiples of 4 found\n"); } if (has_negative) { printf("Product of negative numbers: %lld\n", product_negative); } else { printf("Product of negative numbers: No negative numbers found\n"); } return 0; }
修正点说明
- 初始化所有变量,避免未定义行为
- 调整循环逻辑,确保输入N个有效偶数
- 用单独计数器统计3的倍数数量,用于计算准确平均值
- 使用
long long存储乘积,避免整数溢出 - 增加标记位处理无对应数字的情况(如无4的倍数时输出提示)
- 输出平均值时用
double类型保证精度
内容的提问来源于stack exchange,提问作者Stratos Mantzounis
相关产品推荐
相关产品推荐

