您的目标没有按需要明确说明:
无论哪种方式,您的程序都会因多种原因而失败:
-
if(((n1,n2,n3,n4,n5)%2)==0) 没有任何用处:它只检查最后一个整数是否为偶数。您可以检查所有整数是否与此偶数
if ((n1 | n2 | n3 | n4 | n5) % 2) == 0)
您没有使用大括号对 if 正文中的指令进行分组。与 Python 不同,缩进在 C 中不起作用,您必须在多条指令周围使用大括号(})在if、else、while、for 等之后形成一个块。
这是忽略奇数的代码的修改版本:
#include <stdio.h>
int main(void) {
int n1, n2, n3, n4, n5, sum, count;
// user enters 5 integers
printf("Enter five different positive integers:\n");
// program scans for user input
if (scanf("%d %d %d %d %d", &n1, &n2, &n3, &n4, &n5) != 5) {
printf("Invalid input\n");
return 1;
}
// for each integer, add it if it is even
count = 0;
sum = 0;
if (n1 % 2 == 0) {
sum += n1;
count++;
}
if (n2 % 2 == 0) {
sum += n2;
count++;
}
if (n3 % 2 == 0) {
sum += n3;
count++;
}
if (n4 % 2 == 0) {
sum += n4;
count++;
}
if (n5 % 2 == 0) {
sum += n5;
count++;
}
if (count > 0) {
printf("There are %d even integers in the input, their sum is %d.\n",
count, sum);
} else {
//program prints if there are no even integers for the inputs
printf("There are no even integers in the input.\n");
}
return 0;
}
使用一些更高级的 C 知识,您可以将代码简化为:
#include <stdio.h>
int main(void) {
int n1, n2, n3, n4, n5, sum, count;
printf("Enter five different positive integers:\n");
if (scanf("%d %d %d %d %d", &n1, &n2, &n3, &n4, &n5) != 5) {
printf("Invalid input\n");
return 1;
}
// use the low order bit to test oddness
count = 5 - ((n1 & 1) + (n2 & 1) + (n3 & 1) + (n4 & 1) + (n5 & 1));
sum = n1 * !(n1 & 1) + n2 * !(n2 & 1) + n3 * !(n3 & 1) +
n4 * !(n4 & 1) + n4 * !(n4 & 1);
if (count > 0) {
printf("There are %d even integers in the input, their sum is %d.\n",
count, sum);
} else {
printf("There are no even integers in the input.\n");
}
return 0;
}
但它实际上更复杂,可读性更差,并且没有被证明更有效。
真正的改进是使用循环:
#include <stdio.h>
int main(void) {
int i, n, sum = 0, count = 0;
printf("Enter five different positive integers:\n");
for (i = 0; i < 5; i++) {
if (scanf("%d, &n) != 1) {
printf("Invalid input\n");
return 1;
}
if (n % 2 == 0) {
sum += n;
count++;
}
}
if (count > 0) {
printf("There are %d even integers in the input, their sum is %d.\n",
count, sum);
} else {
printf("There are no even integers in the input.\n");
}
return 0;
}