所以我的编程技巧有点生疏,除了我过去的大学课程之外没有任何真实的世界经验 . 我正在研究一个类的程序,但遇到了障碍;我无法弄清楚如何在循环外的 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
的总和 . 我还想捕获它需要多少次迭代,然后将其输出为周数 . 希望一切都有意义;任何和所有的帮助表示赞赏 .
2 回答
看起来你想要做的事情可以用
ceil(double(need/weekly))
完成,并且需要将每周的分数除以 .在完成
for
循环后,循环外的声明不会影响cout
的值 .至于你的问题,看起来你从未初始化
need
所以你的for循环永远不会进行迭代,因为undefined不小于或等于0 .你的计划的C 11中的草图 .