简体   繁体   中英

How do you use the “%” operator in C++?

I have to take a number of days and convert them into weeks and days.

I know I have to use the % operator, but how do I use it?

% is the modulo (remainder) operator. In your case, try:

int weeks = total_days / 7;
int remaining_days = total_days % 7;    

Odd how when people asking a question say "I know", they're often wrong. You don't need modulus ( % ) at all.

int weeks = total_days / 7;
printf("%d days is equal to %d weeks and %d days.\n",
       total_days, weeks, total_days - weeks*7);

Actually you can divide the total number of days by 7 and you will get the weeks. THen you can perform modulo on total number of days with 7 and you get the days remaining. Is this not enough

% (modulus operator) gives you the remainder. So days % 7 will give you the amount of days left after converting to weeks. ie if days = 15, then days % 7 would equal 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM