我正在尝试编写一个程序,在此程序中向人们添加n天(整数)天后是一天(例如,星期一或其他日期)

问题描述 投票:0回答:1

因此,程序应要求输入一天,然后将其表示为整数值(例如, 0 =星期日或1 =星期一等),然后用户输入n天(例如10天),程序必须找出10天后的哪一天(从星期日到星期六)。 (我知道我可以很轻松地使用循环来解决它,但是我更喜欢不使用它,谢谢。)

 #include <iostream>
    #include <string>
    int main() {

        std::string today;
        std::cout <<"What day is today: " << std::endl;
        std::getline (std::cin, today);

        int d_ay;
        std::cout << "How many days to add ";
        std::cin >> d_ay;

        if (today == "Monday" or 1){
            today = 1 or "Monday";
        } 

        if (today == "Tuesday"){
            today = 2;
        }

        if (today == "Wednesday"){
            today = 3;
        }

        if (today == "Thursday"){
            today = 4;
        }

        if (today == "Friday"){
            today = 5;
        }

        if (today == "saturday"){
            today = 6;
        }

        if (today == "Sunday"){
            today = 0;
        }

        int meet;

        if(d_ay > 6){

            if (d_ay > 20){
                meet = (today + d_ay)/6;
            }
        }

        return 0;
    }

这是我走了多远。

c++ days
1个回答
0
投票

由于"Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday" 重复的周期为每7天,所以d_ay只需要7个案例。

但是,通过使用modulo的概念可以使此过程更加优雅。 Mod由C ++中的%符号表示,并且它们的定义如下:a % b = the remainder when a is divided by b.

例如,4 % 3 = 14 % 2 = 0

现在,我们可以编写一个经过修订的程序:

#include <iostream>
#include <string>

using namespace std;

int main(){
    vector <string> days = {"Monday", "Tuesday", "Wednesday", "Thursday", 
                            "Friday", "Saturday", "Sunday"};

    // Input
    string today;
    cout << "Enter today: ";
    cin >> today;

    int increment;
    cout << "Enter the increment: ";
    cin >> increment;

    int find_day = -1;
    for(int i = 0; i < 7; ++i){
        if(days[i] = today){find_day = i; break;}
    }

    if(find_day == -1){
        cout << "You did not enter a valid day..." << endl;
    }
    else{
        cout << days[(i + increment)%7] << endl;
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.