Ask your own question, for FREE!
Computer Science 7 Online
OpenStudy (anonymous):

help with c++

OpenStudy (anonymous):

so z is a float variable, it says that x = y * z is bad programming style but i don't know why.

OpenStudy (anonymous):

from what i understand i think i have to write it as x = y + (int)z

OpenStudy (e.mccormick):

Like they were talking about, it has to do with rounding errors.

OpenStudy (e.mccormick):

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.

OpenStudy (anonymous):

the entire code section is int x, y = 4; float z = 2.7 x = y * z;

OpenStudy (e.mccormick):

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.

OpenStudy (anonymous):

so i should do (float)x = (float)y + z; ?

OpenStudy (e.mccormick):

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.

OpenStudy (anonymous):

well what do think is the best way to write it?

OpenStudy (anonymous):

I need help with it too. I learned Java script.

OpenStudy (e.mccormick):

If you need to use floats, have them all be floats.

OpenStudy (anonymous):

well im only supposed to change this section x = y * z

OpenStudy (e.mccormick):

Then you would have to cast the float to an int, which will cause loss no matter what.

OpenStudy (anonymous):

okay thx

OpenStudy (e.mccormick):

``` #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

OpenStudy (anonymous):

instead of std::cout can we use using namespace std; before "int main()"

OpenStudy (e.mccormick):

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.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!