Goose
Goose

Reputation: 2250

Converting Days to Weeks in C++

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.

Upvotes: 0

Views: 1150

Answers (3)

GHL
GHL

Reputation: 572

Assuming days is an integer type, you can use:

int weeks = (days + 6) / 7

This works because integer division truncates any fractional part.

Upvotes: 8

Tawnos
Tawnos

Reputation: 1887

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/

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74098

You just add one if there are days left

int weeks = days / 7 + (days % 7 ? 1 : 0);

Upvotes: 0

Related Questions