Our activity requires to input 4 numbers, positive or negative and only add the negative numbers.
Example:
-30.22
10.50
-2.2
-1.8
Result is -34.22
which sums up the negative numbers only.
We have not discussed the loop or array at this moment. Is it possible to solve in a mathematical equation? I can’t seem to find any answers if I try to code it.
Can it be solved using if-else-elseif statements?
CodePudding user response:
Read the input into four variables, then use four if
statements to add them to the total when they're negative.
float a, b, c, d;
scanf("%f %f %f %f", &a, &b, &c, &d);
float total = 0;
if (a < 0) {
total = a;
}
if (b < 0) {
total = b;
}
if (c < 0) {
total = c;
}
if (d < 0) {
total = d;
}
printf("%.2f\n", total);
You can also use the conditional operator.
float total = (a < 0 ? a : 0) (b < 0 ? b : 0) (c < 0 ? c : 0) (d < 0 ? d : 0);
CodePudding user response:
These assignments some teachers invent are really pathetic.
Maybe you want this:
#include <stdio.h>
int main(void)
{
float a, b, c, d;
scanf("%f %f %f %f", &a, &b, &c, &d);
float total = (a < 0 ? a : 0) (b < 0 ? b : 0) (c < 0 ? c : 0) (d < 0 ? d : 0);
printf("%f", total);
}
No loops, no if/else.
But be aware that this is really terrible code.
CodePudding user response:
A solution that doesn't use neither if
nor while
(and co.)
int main(void) {
float n1 = 0, n2 = 0, n3 = 0, n4 = 0;
printf("Insert first number: ");
scanf("-%f", &n1);
scanf("%*[^\n]");
printf("Insert second number: ");
scanf(" -%f", &n2);
scanf("%*[^\n]");
printf("Insert third number: ");
scanf(" -%f", &n3);
scanf("%*[^\n]");
printf("Insert fourth number: ");
scanf(" -%f", &n4);
scanf("%*[^\n]");
float sum = -n1 - n2 - n3 - n4;
printf("Sum of all negative numbers: %f\n", sum);
return 0;
}
Explanation
scanf("-%f", &n1)
will have two possible behaviors:
- in case of positive numbers (e.g.:
3.14
or1.2
), it will fail to parse the input (because it isn't able to match the first-
symbol), so variablen1
stays0
; - in case of negative numbers (e.g.:
-5
or-3.1
), it will match the minus symbol and put the rest of the number inton1
(son1
is either5
or3.1
, for instance).
Basically, for all four numbers, if the user input is positive, n
is 0
; if the input is negative, n
is the absolute value of the number (2.0
instead of -2.0
etc).
scanf("%*[^\n]")
will clear the input buffer after (possible) positive numbers (because scanf()
won't match positive numbers).
float sum = -n1 - n2 - n3 - n4
is a (weird) "sum", but necessary since all four numbers are either 0
or the negation of a negative number.