help with c++
so z is a float variable, it says that x = y * z is bad programming style but i don't know why.
from what i understand i think i have to write it as x = y + (int)z
Like they were talking about, it has to do with rounding errors.
Know how in decimal 1/3 is an ininite sequence of .3? Well, there are things like that in binary too. So these add up pretty qick as mistakes in the math.
the entire code section is int x, y = 4; float z = 2.7 x = y * z;
Well there you are going to truncate the float because you are multiplying a float times an int as assigning to a float. That will cause loss.
so i should do (float)x = (float)y + z; ?
Well, you would still have ussues. It is simply best to never mix floats and ints. Floats are always estimates and ints are always exact.
well what do think is the best way to write it?
I need help with it too. I learned Java script.
If you need to use floats, have them all be floats.
well im only supposed to change this section x = y * z
Then you would have to cast the float to an int, which will cause loss no matter what.
okay thx
``` #include <iostream> int main() { int x1, y1=4; float z1=2.7; x1 = y1 * z1; float x2, y2=4; float z2=2.7; x1 = y1 * z1; x2 = y2 * z2; std::cout << "As ints\n"; std::cout << x1 << std::endl; std::cout << "\nAs floats\n"; std::cout << x2 << std::endl; getchar(); return 0; } ``` As ints 10 As floats 10.8
instead of std::cout can we use using namespace std; before "int main()"
Yes, you can set the namespace. Over the long term, you will get away from loading an entire namespace when you only need a few packages from it.
Join our real-time social learning platform and learn together with your friends!