![]() |
C++ strange arithmetic?
Why is it that when I add two integers values(5 and 2),divide them by two and assign the result to a float value,
that the float value refuses to have decimals? ex: :
#include <iostream> |
cast the parethesis to float
|
When you add number1 and number2 (both being of type int), the result of the calculation is int.
When you divide an integer by another integer, you will also end up with an integer (hence your answer of 3 -- the remainder is ignored). The solution (like Mrafcho001 said), is to cast number1 + number2 as a float. :
|
Good thing to know! Could have messed me up later on. I've been practicing c++ for a good couple weeks and never knew that....
|
Quote:
|
Quote:
|
No attempt to denigrate you, it just sounds funny, "a good couple weeks, now." Think of it like this, it'll make sense: you operate with two integers. The result is an integer. THEN the assignment is made; a promotion takes place, but there's no fractional value to promote. If you cause the promotion to take place FIRST, you're walking in tall cotton. Besides learning syntax, which is really about all you've had time for, you might want to skim some more esoteric things, such as precedence of operations. In other words, given more than one way to do things, or more than one possible order to do them in, what have the language's authors decided? It's additional effort, but it might pay off in fewer mysteries while you progress.
|
You shouldn't be so negative to beginers... Once you didn't know anything either. He'll learn.
|
Things you will look back on and wish you hadn't said:
Quote:
|
Quote:
|
| All times are GMT -5. The time now is 9:30 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC