 |
 |
why can't I do simple math?
|
 |
|
 |
|
Professional Poster
Join Date: Sep 2000
Location: San Francisco
Status:
Offline
|
|
Code:
float progressIndicator;
progressIndicator=17/400*100;
NSLog(@"progressIndicator=%f",progressIndicator);
This results in progressIndicator being 0. What am I doing wrong?
kman
|
|
|
| |
|
|
|
 |
|
 |
|
Mac Enthusiast
Join Date: Feb 2003
Location: Portland, Oregon
Status:
Offline
|
|
I still don't know objective-C well, but could it be as simple as missing parenthesis around the math?
progressIndicator = ( 17/400*100 );
|
|
|
| |
|
|
|
 |
|
 |
|
Mac Elite
Join Date: Sep 2000
Location: Tempe, AZ
Status:
Offline
|
|
Your code is standard C. In standard C, when you do integer math, you get an integer answer. Using all integers, 17/400 is zero (it's .0425 - truncate the non-integer portion and you get zero).
In standard C, an arithmetic operation's resulting type is dependent upon the types used within that operation. So, if you used 17.0 / 400 instead of 17 / 400, you'd get a fraction. Adding the '.0' tells the compiler "even though this number is an integer, I want you to treat it as a float". You could get the same result using (float)17 / 400.
The rule of thumb when using constants in a math expression is: If you want the answer to be a float, use constants that are explicitly floats. If not, don't.
For more info, consult any book about C and look for the section on 'expressions'.
|
Geekspiff - generating spiffdiddlee software since before you began paying attention.
|
| |
|
|
|
 |
|
 |
|
Professional Poster
Join Date: Sep 2000
Location: San Francisco
Status:
Offline
|
|
Originally posted by smeger:
Your code is standard C. In standard C, when you do integer math, you get an integer answer. Using all integers, 17/400 is zero (it's .0425 - truncate the non-integer portion and you get zero).
In standard C, an arithmetic operation's resulting type is dependent upon the types used within that operation. So, if you used 17.0 / 400 instead of 17 / 400, you'd get a fraction. Adding the '.0' tells the compiler "even though this number is an integer, I want you to treat it as a float". You could get the same result using (float)17 / 400.
The rule of thumb when using constants in a math expression is: If you want the answer to be a float, use constants that are explicitly floats. If not, don't.
For more info, consult any book about C and look for the section on 'expressions'.
Thanks!
|
|
|
| |
|
|
|
 |
 |
|
 |
|
|
|
|
|

|
|
 |
Forum Rules
|
 |
 |
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
|
HTML code is Off
|
|
|
|
|
|
 |
 |
 |
 |
|
 |
|