问题:
编写程序以计算整数x的分数。如果x为零或负数,则分数为-100。否则,我们从0开始。如果x是3的倍数,则将3加到分数上。之后,如果x是5的倍数,则将5加到分数上。之后,如果x在100到200(含)之间,则将分数加50,否则从分数中减去50。现在打印分数。
我的问题:
下面的解决方案有效,但是我找不到更简洁的方法来编写解决该问题的程序。我是C语言的新手,但我的理解是 Switch语句不能进行逻辑比较,并且只要满足 If语句,就不会再进行检查了。 。
有没有一种方法可以在不重复代码块的情况下针对多个规则检查整数? -谢谢。
我的解决方案:
#include <stdio.h>
int main()
{
int x;
int score;
scanf("%d", &x);
if (x <= 0){
score = -100;
}
else {
score = 0;
if (x % 3 == 0 && x % 5 == 0) {
score += 8;
if (x >= 100 && x <= 200) {
score += 50;
}
else {
score -= 50;
}
}
else if (x % 3 == 0) {
score += 3;
if (x >= 100 && x <= 200) {
score += 50;
}
else {
score -= 50;
}
}
else if (x % 5 == 0) {
score += 5;
if (x >= 100 && x <= 200) {
score += 50;
}
else {
score -= 50;
}
}
else if (x >= 100 && x <= 200) {
score += 50;
}
else {
score -= 50;
}
}
printf("%d", score);
return 0;
}
答案 0 :(得分:3)
您要做的事情超出了必要:所有3个条件检查必须始终进行,因此不需要在链接的if-else语句内嵌套if语句。
当我们对问题的格式稍有不同时,解决方案实际上更加清晰:
Otherwise we start with 0. If the x is a multiple of 3, add 3 to the score. After that if x is a multiple of 5, add 5 to the score. After that if x is between 100 and 200 (inclusive), add 50 to the score, else subtract 50 from the score.