c++ - 如何实现递增数据的循环

标签 c++ loops for-loop

<分区>

我试图通过在 C++ 中使用循环来使我的程序更智能。试图解决这个问题时我遇到了精神障碍,因为我试图跟踪这么多计数器。比正确的代码更重要的是,我如何正确地思考问题以得出正确的结论?

我已经尝试了 for 循环并认为嵌套的 for 循环可能是必要的,但我不知道如何不断添加 monthDays[] 值以正确检查输入并做出正确的决定。

输入是小于 366 但大于 0 的用户定义数字。 该程序旨在返回月份名称和该月份过去的天数。

string monthNames[12] = {"January", "February", "March", "April"};
int monthDays[12] = {31, 28, 31, 30};   


if ((input - monthDays[0]) <=  0){

    cout << monthNames[0] << " " << input;
    }

      else if (input < (monthDays[0] + monthDays[1]) &&  
              (input > monthDays[0]){

        cout << monthNames[1] << " " << (input - monthDays[0]);
     }

        else if (input < (monthDays[0] + monthDays[1] + monthDays[2]) &&
                input > (monthDays[0] + monthDays[1])){

          cout << monthNames[2] << " " << (input - monthDays[0] - monthDays[2]);
        }

          else if (input < (monthDays[0] + monthDays[1] + monthDays[2] + monthDays[3]) &&      
                  input > (monthDays[0] + monthDays[1] + monthDays[2])){

       cout << monthNames[2] << " " << (input - monthDays[0] - monthDays[2] - monthDays[3]);
           }

该程序可以运行,但可以简化。我应该如何改变我的思维过程来实现循环?

最佳答案

我假设你想打印“month day”,所以你可以将你的逻辑简化为:

string monthNames[12] = {"January", "February", "March", "April", /*and so on*/}; 
int monthDays[12] = {31, 28, 31, 30, /*same here*/}; 
int i = 0;
/*While your input is bigger than the days of the month*/    
while(input > monthDays[i] && i < 12)
{
    input -= monthDays[i]; // subtract it
    i++;                   // and go to next month
}
//Then print the month and the day
cout << monthNames[i] << " " << input;

关于c++ - 如何实现递增数据的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682347/

相关文章:

c++ - (1 << 27) 的十六进制值是多少?

c++ - hackerrank 项目 euler #1 由于超时而终止

c++ - MurmurHash3 是否可以生成高 32 位全为 0 的 64 位哈希?

c++ - 所有可能的毕达哥拉斯三元组

php - 模型->保存()在 Yii 中不起作用 -> 显示 ' error '

c++ - boost 递归对象的序列化

html - css 动画 - 鼠标顺利移出

function - zsh:找不到命令:ls

python - Bash 脚本在 python 变量上循环

java - 为什么我的 for 循环不会添加超过 1.0/10,000,000.0 的分数?