0

I am trying to convert a total amount of X days into X amount of weeks in C++, this is what I've seen done online and is not working:

int weeks = ((days % 365) / 7);

For example, if days = 8, then technically it is onto week 2 so int weeks should be = 2. Similarly 15 days should output 3.

Thanks.

4

3 回答 3

8

Assuming days is an integer type, you can use:

int weeks = (days + 6) / 7

This works because integer division truncates any fractional part.

于 2013-02-01T00:37:28.683 回答
1

Integer division will truncate the result. In order to get the number of weeks, you'll need to take the ceil of the division. If you only want those days that represent weeks within a year, you keep the mod, else, don't.

In other words:

int weeks = (int)ceil(days / 7.0);

http://www.cplusplus.com/reference/cmath/ceil/

于 2013-02-01T00:39:28.980 回答
0

You just add one if there are days left

int weeks = days / 7 + (days % 7 ? 1 : 0);
于 2013-02-01T00:37:47.657 回答