【问题标题】:how do I use the variable from a For loop outside the loop in C++?如何在 C++ 中的循环外使用 For 循环中的变量?
【发布时间】:2014-10-08 16:22:16
【问题描述】:

所以我的编程技能有点生疏,除了我过去上过的大学课程外,没有任何现实世界的经验。我正在为一个类编写程序,但遇到了障碍;我无法弄清楚如何在循环外的For 循环内使用变量的值。这是我引用的代码:

#include "iostream"

using namespace std;

int want, have, need;
int counter = 0;

char response, cont;

int diff(int want, int have);

int main(){
cout << "Welcome!\n";
cout << "This program will help you reach your money saving goals!\n";
cout << "Would you like to use this program? (y/n)\n";
    cin >> response;
    while (response == 'y'){
        cout << "Please enter all amounts in whole dollars only!\n";
        cout << "Please enter the amount of money you would like to have saved: $";
        cin >> want;
        cout << "\nPlease enter the amount of money you currently have saved: $";
        cin >> have;
        if (have >= want){
            cout << "You have already reached or exceeded your goal, this program will not be able to help you!\n";
            system("Pause");
            return 0;
        }
        cout << "\nYou need to save $" << diff(want, have) << " more money to reach your goal!\n";
        cout << "Would you like me to help you with a savings plan?";
        cin >> cont;
        while (cont == 'y'){
            int menu;
            cout << "Please select from the following options: \n";
            cout << "1 - Daily Saving Plan\n";
            cout << "2 - Weekly Saving Plan\n";
            cout << "3 - Monthly Saving Plan\n";
            cout << "Enter the number associated with your choice: \n";
            cin >> menu;

            switch (menu){
                case 1: {
                    int daily;
                    cout << "You have chosen the Daily Savings Plan\n";
                    cout << "How much money can you save every day? $";
                    cin >> daily;
                    for (int x = daily; x < need; x++){
                        daily = daily + daily;
                        counter++;
                    }
                    cout << "\nIt will take you " << counter << " days to reach your goal!\n";
                    break;
                }
                case 2: {
                    int weekly;
                    cout << "You have chosen the Weekly Savings Plan\n";
                    cout << "How much money can you save every week? $";
                    cin >> weekly;
                    for (int x = weekly; x < need; x++){
                        counter++;
                    }
                    cout << "\nIt will take you " << counter << " weeks to meet your goal!\n";
                    break;
                }
                case 3: {
                    int monthly;
                    cout << "You have chosen the Monthly Savings Plan\n";
                    cout << "How much money can you save every month? $";
                    cin >> monthly;
                    for (int x = monthly; x < need; x++){
                        monthly = monthly + monthly;
                        counter++;
                    }
                    cout << "\nIt will take you " << counter << " months to reach your goal!\n";
                    break;

                }
                default: cout << "You made an invalid selection";

                    cout << "Would you like to look at a different saving plan? (y/n)\n";
                    cin >> cont;
            }
        }
    }
}

int diff(int want, int have){
return want - have;
}

所以,当我运行程序时,一切正常,但在最后的cout 语句中,计数器的值始终显示为“0”。

我想我理解它为什么这样做,这是因为循环外的“int counter = 0”声明,所以我假设循环退出后它会回到那个值。

如果我不启动计数器变量,我会得到一个错误,如果我在循环中声明该值,我会得到一个错误,试图在上面的 cout 语句中使用它。

我什至不确定我的 for 循环结构是否正确...基本上我希望它自己添加每周变量,直到总数为 x = need。我还想捕获它需要多少次迭代,然后将其输出为周数。希望一切都说得通;感谢您提供任何和所有帮助。

【问题讨论】:

  • 重现问题的邮政编码。
  • 不,counter 在循环后不会归零。如果它为零,那是因为它从未增加过。在循环开始之前检查weeklyneed 的值。
  • 对于初学者,我会尝试在函数开始时在开关外声明计数器。在循环开始之前应该有初始化:counter=0;
  • 另外,像counter = need&gt;weekly ? need-weekly : 0 这样的算术可能比循环更清晰(更快)。
  • “所以我假设 [...]” - 这是您在编程时可能犯的最大错误之一。始终验证您的假设。

标签: c++ loops variables for-loop


【解决方案1】:

似乎您想做的事情可以用ceil(double(need/weekly)) 完成,并且将需求除以每周。

在您完成for 循环后,您在循环外的声明不会影响您cout 的值。

至于您的问题,您似乎从未初始化 need,因此您的 for 循环从未进行过迭代,因为 undefined 不小于或等于 0。

【讨论】:

    【解决方案2】:

    你的程序的 C++11 草图。

    char prompt( std::initializer_list<const char*> message, std::initializer_list<const char*> question, std::initializer_list<char> options ) {
      for( auto msg:message )
        std::cout << msg;
      while(true) {
        char response;
        for( auto q:question)
          std::cout << q;
        std::cin >> response;
        for (char option:options) {
          if (response == option)
            return response;
        }
      }
    }
    int prompt( std::initializer_list<const char*> message, std::initializer_list<const char*> question, int min = 0, int max = std::numeric_limits<int>::max() ) {
      for( auto msg:message )
        std::cout << msg;
      while(true) {
        int response;
        for( auto q:question)
          std::cout << q;
        std::cin >> response;
        if (response >= min && response <= max)
          return response;
        }
      }
    }
    void saving( const char* plan, const char* unit, const char* units, int target ) {
      int daily = prompt(
        {"You have chosen the ", plan,  "\n"},
        {"How much money can you save every ", unit, "? $"}, 
        1 // min saving of 1$ per unit time to prevent infinite loops
      );
      std::cout  << "\n";
      int counter = 0;
      int amount_saved = 0;
      while (amount_saved < target) {
        ++counter;
        amount_saved += daily;
      }
      if (counter != 1)
        std::cout << "It will take you " << counter << " " << units << " to reach your goal\n";
      else
        std::cout << "It will take you " << counter << " " << unit << " to reach your goal\n";
    }
    
    int main() {
      while(
        prompt(
          {"Welcome!\nThis program will help you reach your money saving goals!\n"},
          {"Would you like to use this program? (y/n)\n"},
          {'y', 'n'}
        ) == 'y'
      )
      {
        int want = prompt( {"Please enter all amounts in whole dollars only!\n"},
          {"Please enter the amount of money you would like to have saved?"} );
        int have = prompt( {"\n"}, {"Please enter the amount of money you currently have saved?\n"} );
        std::cout << "\n";
        if (have >= want) {
          std::cout << "You win!\n";
          system("Pause"); // ick
          return 0;
        }
        std::cout << "You need to save $" << (have-want) << " more money to reach your goal!\n";
        while( 'y' == prompt(
          {},
          {"Would you like me to help you with a savings plan? (y/n)"},
          { 'y', 'n' }
        )) {
           char menu = prompt(
             {
               "Please select from the following options: \n",
               "1 - Daily Saving Plan\n",
               "2 - Weekly Saving Plan\n",
               "3 - Monthly Saving Plan\n"
             },
             {"Enter the number associated with your choice: \n"},
             { '1', '2', '3' }
           );
           switch (menu) {
             case '1': {
               saving( "Daily Saving Plan", "day", "days", have-want);
             } break;
             case '2: {
               saving( "Weekly Saving Plan", "week", "weeks", have-want);
             } break;
             case '3': {
               saving( "Monthly Saving Plan", "month", "months", have-want);
             } break;
           }
    
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      相关资源
      最近更新 更多