你的目标并未明确需要指出:
无论哪种方式,你的程序出于多种原因失败:
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;
}
尝试使用数组和循环。在所有情况下。 – Peter