views:

124

answers:

6

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!?

+4  A: 

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).

Bill the Lizard
A: 

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.

Samuel Carrijo
A: 

The 60.0 forces a conversion to double try:

float seconds = 200;

float mins = seconds / 60;

float sec = mins % 60;
Andrew Cox
This still doesn't work; mins is a float.
David Coufal
+4  A: 

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... :)

roe
A: 

Do like this:

float seconds = 200.5;

float mins = floor(seconds / 60.0);

float sec = seconds - mins * 60.0;
e.tadeu
A: 

Thanks Everyone This works great!

int seconds = [timeIndexSlider value];

int mins = seconds / 60;

int sec = seconds % 60;

[timeIndexLabel setText:[NSString stringWithFormat:@"%d.%d", mins,sec]];
Chris
You probably got downvoted for this (not by me) because standard procedure is to accept the correct answer (if one is given), not restate it as your own answer. I suggest **roe**'s answer, since he caught the math error as well as the ints. (You should be able to delete this answer on your end as well.)
Quinn Taylor