I wanted to write a little calculator, which I have already done by using cout
and cin
, and I used double
instead of int
to not only get integers as an output.
At school, I then saw that we're going to use printf()
and scanf()
. To practice the new commands, I wanted to rewrite my program, but when I run my program I only see a lot of zeros after the comma as an output. Does anybody know why?
I wanted to rebuild a calculator with double
instead of int
to not only get integers as a result.
This is the code:
#include <stdio.h>
using namespace std;
int main(){
printf ("Taschenrechner\n\n");
int zahl1, zahl2;
char rechop;
double erg;
printf ("Gib die Rechnung ein: ");
scanf ("%d", &zahl1);
scanf ("%c", &rechop);
scanf ("%d", &zahl2);
if (rechop == ' '){
erg = zahl1 zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else if (rechop == '-'){
erg = zahl1 - zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else if (rechop == '*'){
erg = zahl1 * zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else if (rechop == '/'){
erg = zahl1 / zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else {
printf ("Keine gültige Rechenoperation!");
}
return 0;
}
CodePudding user response:
To decide how many decimal numbers show, you can use %.2f
(where ".2" stands for "2 decimals after the comma") in the printf instead of simply %f
.
Edit: forgot to say that, by doing that, your result get rounded (and not simply "cut").
There is your code updated (and translated):
#include <stdio.h>
using namespace std;
int main(){
printf ("Calculator\n\n");
int num1, num2;
char simbol;
double res;
printf ("Insert the expression: ");
scanf ("%d", &num1);
scanf ("%c", &simbol);
scanf ("%d", &num2);
if (simbol == ' '){
res = num1 num2;
printf ("Result : ");
printf ("%.2f", res);
}
else if (simbol == '-'){
res = num1 - num2;
printf ("Result : ");
printf ("%.2f", res);
}
else if (simbol == '*'){
res = num1 * num2;
printf ("Result : ");
printf ("%.2f", res);
}
else if (simbol == '/'){
res = num1 / num2;
printf ("Result : ");
printf ("%.2f", res);
}
else {
printf ("Not a valid expression!");
}
return 0;
}
CodePudding user response:
Your output has zeros after the decimal point, because that's actually what is in the variable (erg
) that you are printing.
Your problem is that this line uses integer division:
erg = zahl1 / zahl2;
When the compiler is picking which operation to do, it only looks at the data type of the inputs (which are both int
). The result is then converted to be stored into erg
, but that doesn't affect the division behavior chosen.
Change the line to:
erg = zahl1 * 1.0 / zahl2;
or
erg = zahl1;
erg /= zahl2;
so that one of the inputs will be type double
, and integer division will no longer be involved.