好的,所以我正在尝试编写一个程序来检查一个数字是否可以被 2、3、4 或 5 整除。
例如,如果用户输入 8,输出将是:
“8能被2整除” “8能被4整除”
我的程序:
#include<stdio.h>
#include<conio.h>
main(){
int num, even, oddThree, evenFour, oddFive;
printf("Please Enter A number: ");
scanf("%d",&num);
even = (num % 2 == 0);
oddThree = (num % 3 == 0);
evenFour = (num % 4 == 0);
oddFive = (num % 5 == 0);
if (even){
printf("%d is divisible by 2\n",num);
}
if(oddThree) {
printf("%d is divisible by 3\n",num);
}
if (evenFour){
printf("%d is divisible by 4\n", num);
}
if (oddFive){
printf("%d is divisible by 5\n", num);
}
else {
printf("%d is not divisible by 2,3,4 or 5\n", num);
}
getch();
}
出于某种原因,当我输入某些数字时,例如 12。我的输出是:
“12能被2整除” “12能被4整除” “12 不能被 2、3、4 或 5 整除”
前两个陈述是正确的,但第三个是错误的。
我做错了什么?
最佳答案
printf("%d is not divisible by 2,3,4 or 5\n", num);
将一直运行
(oddFive)
是错误的。 也许
if (!(even || oddThree || evenFour || oddFive)) {
printf("%d is not divisible by 2,3,4 or 5\n", num);
}
关于c - 基础编程 C 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31388326/