+ 3
How to use decimals in C++?
This code calculates how much a client gets back in different denominations of money but the last one with decimals is written wrong. I tested to change the data type of variable "half" to double but then it messes up alla the code. https://code.sololearn.com/cyh75IUMW5Qb/?ref=app
9 odpowiedzi
+ 5
The problem is that you cast whole expression, when you should cast only "back" like that:
back = int(back) % 10; // C type-casting
In addition, in last three if statements:
int half = 1;
Should be just "half = 1;"
Cuz you are declaring new variable here, which lives only in scope of that "if".
C++ type casting should look like this in above example:
back = static_cast<int>(back) % 10;
Both works well, but this one is safer
+ 8
1. "back", "price", "received" and "half" should be double type
2. you get random numbers as output, because you did not assign any value to variables at the beginning. So if, for example, "hundred" will not get any value in "if" statement, you will find garbage value at the output.
3. If you cast "back" to double, as it should be, you will not be able to use % operator, so you'll have to cast "back" to int every time you use it.
Anyway, "price", "received", "back" and "half" should be of type double/float, and you must assign values to all the variables that you will output to avoid garbage
+ 4
It would make sense that it's not working, because int%int=int, so I don't think it's even possible to use modulo with float variables
+ 3
Hi! Thanks for your answer.
I solved the problem with fmod() instead modulus but I would like to solve this with modulus. You see I changed the code but it doesn't work. Can anyone help me with that?
One question till: why do I need assign values to int variables in the beginning if I don't use them until I assign them a value in "if" statements?
+ 3
Thanks a lot. This is the explanation I wanted to get.
int x = infinity;
int i;
while(x != i) { cout << "thanks\n"; i++;}
+ 3
Pozik, after a few tests, it still does not work well, so I moved "half" to the top, so it will get assigned first in case of rounding "back" to integer:
https://code.sololearn.com/c3fhnlUgnex6/?ref=app
+ 3
Cleverly done with "back" - static_cast(back) , the code looks better now. Otherwise it's strange that it didn't work for you how it is because it works for me. Should the code really work properly if after we cast the variable to an integer it would lose the rest of the digits?
+ 2
Just tested once again and you was right the last tre with digits doesn't work.
0
Ok sir c++ meaning