2014-10-08 8 views
0

저는 프로그래밍 기술에 다소 녹슬었고 과거에 찍은 대학 수업을 제외한 실제 경험이 없습니다. 나는 클래스를위한 프로그램을 만들고 있지만 걸리는 부분에 뛰어 들기 때문에 루프 밖에서 For 루프 안에서 변수 값을 사용하는 방법을 알 수 없다.C++의 루프 외부에서 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 루프가 올바르게 구조화되어 있는지 확신 할 수 없습니다. 기본적으로 매주 변수를 추가하려고합니다. 즉, 까지입니다. 또한 얼마나 많은 반복을 포착하여 주 단위로 출력하고 싶습니다. 바라기를 모든 것이 의미가 있습니다. 모든 도움을 주시면 감사하겠습니다.

+0

문제를 재현하는 코드입니다. –

+7

아니요, 'counter'는 루프 이후에 0으로 돌아 가지 않습니다. 0 인 경우 증가하지 않았기 때문입니다. 루프가 시작되기 전에'weekly'와'need'의 값을 확인하십시오. 우선 –

+0

에 대해, 나는 함수 밖에서 카운터를 선언하려고 시도 할 것이다. 루프가 시작되기 전에 초기화가 있어야합니다 : counter = 0; – user3621602

답변

0

당신이하고 싶은 일은 ceil(double(need/weekly))으로 할 수 있으며 매주마다 필요를 반올림하여 나눌 수 있습니다.

for 루프를 완료 한 후 루프 외부에 선언하면 cout 값에 영향을주지 않습니다. 문제에 관해서는

, 그것은 당신이 초기화 결코처럼 보이는 need 그래서 당신의 정의는 C++ (11) 프로그램의 0로

0

스케치 이하로 나오지 않을 것 같은 루프 반복을 만든 적이을 위해.

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; 
     } 

    } 
    } 
} 
관련 문제