你的目標並未明確需要指出:
無論哪種方式,你的程序出於多種原因失敗:
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