Reputation:
I am trying to display minutes and seconds based on a number of seconds.
I have:
float seconds = 200;
float mins = seconds / 60.0;
float sec = mins % 60.0;
[timeIndexLabel setText:[NSString stringWithFormat:@"%.2f , %.2f", mins,seconds]];
But I get an error: invalid operands of types 'float' and 'double' to binary 'operator%'
And I don't understand why... Can someone throw me a bone!?
Upvotes: 1
Views: 227
Reputation: 35667
As others have pointed out, you should be using integers. However, noone seems to have spotted that the result will be incorrect. Go back and have another look at modulo arithmetic, and you'll realize you should be doing
int seconds = 200;
int mins = seconds / 60;
int sec = seconds % 60;
Note the last line, seconds % 60
rather than mins % 60
(which will return the remainder of the minutes divided by 60, which is the number of minutes to the hour, and completely unrelated to this calculation).
EDIT
doh, forgot the ints... :)
Upvotes: 4
Reputation: 5328
Do like this:
float seconds = 200.5;
float mins = floor(seconds / 60.0);
float sec = seconds - mins * 60.0;
Upvotes: 0
Reputation: 17929
Use ints instead. At least in your example, seems like they're enough (it will also be faster and clearer).
Also, in this case you would get 3.3333... mins, and not 3 minutes as expected. You could use Math.ceil(x) if you need to work with floats.
Upvotes: 0
Reputation: 405785
A lot of languages only define the % operator to work on integer operands. Try casting seconds
and mins
to int
before you use % (or just declare them int
in the first place). The constant values you use will also need to be int
(use 60 instead of 60.0).
Upvotes: 4
Reputation: 10988
The 60.0
forces a conversion to double
try:
float seconds = 200;
float mins = seconds / 60;
float sec = mins % 60;
Upvotes: 0