Problem:
Write a program to compute a score for an integer x. If x is zero or negative the score is −100. 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. Now print the score.
My Question:
The solution below works, but I can't find a more concise way to write a program that solves the problem. I'm new to C but my understanding is that Switch Statements can't do logical comparisons, and that as soon as an If Statement is met, no further ones are checked.
Is there a way to check an integer against multiple rules without repeating the code blocks? - Thank you.
My Solution:
#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;
}
Aucun commentaire:
Enregistrer un commentaire