Can someone help me solve this exercise on programming with C language on Dev-C++? [closed]
Write a program that reads numbers until you r开发者_开发问答ead the number 999 then the process stops reading. Therefore use do while. Then display the sum of two digit numbers, both positive and negative that were imported in the computer and the number of numbers that were imported to the computer overall.
When I insert the number 999 the process stops. That works fine. I'm sure that the if command is wrong cause it doesn't add any numbers in sum. I run it and it prints out that the sum of the two digit numbers is 0.
int num1, a, sum;
a = 0;
sum = 0;
do
{
printf("give number\n");
scanf("%d", &num1);
a = a + 1;
if ((num1>=-99) && (num1<=-10) && (num1>=10) && (num1<=99))
{
sum = sum + num1;
}
printf("the sum of the two digit numbers is %d\n", sum);
}
while (num1 != 999);
printf("the sum of the two digit numbers is %d\n", athr);
printf("the number of numbers that were inserted overall is %d\n", a);
Your if
statement can never be true:
if ((num1>=-99) && (num1<=-10) && (num1>=10) && (num1<=99))
since the two valid ranges don't overlap and you're using &&
to 'combine' them.
Use
if (((-99 <= num1) && (num1 <= -10)) || ((10 <= num1) && (num1 <= 99)))
instead.
My readability tip of they day: note that I slightly rejiggered the comparisons. The range comparisons mirror a little more closely how they might look in algebraic notation:
(-99 <= num1 <= -10) or (10 <= num1 <= 99)
It's a small thing, but I find it makes a big difference to being able to follow the logic of these kinds of tests. Just don't fall into the trap of coding this:
if ((-99 <= num1 <= -10) || (10 <= num1 <= 99))
Which, unfortunately, is syntactically valid in C/C++ but will not give you the results you want.
(num1>=-99) && (num1<=-10) && (num1>=10) && (num1<=99)
How can a number satisfy all these conditions ? For instance, (num1<=-10) && (num1>=10)
think of a number which can satisfy these two conditions ?
Can num1
be both <-10 and >10 ?
Your condition
(num1>=-99) && (num1<=-10) && (num1>=10) && (num1<=99)
can never be true
, because no number can both be negative (<=-10
) and positive (>=10
).
You messed up the check for two-digitness:
You did
(-99 <= n <= -10) AND (10 <= n <= 99)
You should have done
(-99 <= n <= -10) OR (10 <= n <= 99)
(Or is ||
in C)
The problem is your if statement. Let's try it with 2 arbitrary 2 digit numbers. -42 and 42.
For negative 42:
true true false false
((num1>=-99) && (num1<=-10) && (num1>=10) && (num1<=99))
Positive 42:
false false true true
((num1>=-99) && (num1<=-10) && (num1>=10) && (num1<=99))
if you include math.h, you could simplify this to:
if (fabs(num1) >= 10 && fabs(num1) <= 99){
sum = sum + num1;
}
Although I'm guessing C++ also has support for += as well.
精彩评论