简体   繁体   中英

Number lines and modulus C++

I am trying to make the opposite of case 3. So the idea is that you can say "x amount of days from sat will be _" . This works well in my case 3 so I figured the same would work if you wanted to solve "x days before sat will be _ ". Now my case 4 only works till a input of 6 then you enter negative numbers which I did not thick about when making this... And my program is based off a array char dayChar[7][4] {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; so has you can see case 4 does not really work. Any suggestions on how to what I could do that would work? Thanks a ton in advance.

case 3: // Add days
                cout << "Day selected is " << day << endl;
                cout << "How many days would you like to add?" << endl;
                cin >> addOrSub;

                temp = (dayNum + addOrSub);
                dayNum = (temp % 7);

                cout << addOrSub << " days from " << day << " will be " << dayChar[dayNum] << endl; 


                break;

            case 4: // Subtract days
                cout << "Day selected is " << day << endl;
                cout << "How many days would you like to subtract?" << endl;
                cin >> addOrSub;

                temp = (dayNum - addOrSub);
                dayNum = (temp % 7);

                cout << addOrSub << " before " << day << " was " << dayChar[dayNum] << endl;

A simple solution is to do: dayNum = ((temp % 7) + 7) % 7;

Since temp % 7 is guaranteed to be greater than -7, adding 7 is guaranteed to give you a positive number, equivalent to the original (modulo 7). The resulting number, though, may be greater than 7, which is why an additional modulo operation is necessary.

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