编写一个程序来衡量过去一年的通货膨胀率。该程序询问一年前和今天的商品(例如热狗或 1 克拉钻石)的价格。它将通货膨胀率估计为价格差除以一年前的价格。程序应允许用户根据需要重复此计算。定义一个函数来计算通货膨胀率。通货膨胀率应该是双精度类型的值,以百分比形式给出率,例如 5.3 表示 5.3%。
程序必须使用函数来计算通货膨胀率。不使用函数的程序将被授予零分,即使所有测试都通过。
我想重复循环,但难怪我输入 Y 或 N,循环也会重复。假设当我输入"Y"或"y"时,循环应该重复。谁能告诉我我的代码出了什么问题?
#include <iostream>
#include <cmath>
using namespace std;
double calculate_inflation(double, double);
int main()
{
double yearAgo_price;
double currentYear_price;
double inflation_Rate;
char again;
do{
cout << "Enter the item price one year ago (or zero to quit) : " << endl;
cin >> yearAgo_price;
cout << "Enter the item price today: " << endl;
cin >> currentYear_price;
cout.setf(ios::fixed)
cout.setf(iOS::showpoint);
cout.precision(2);
inflation_rate=calculate_inflation(yearAgo_price, currentYear_price);
cout << "The inflation rate is " << (inflation_rate*100) << " percent." << endl;
cout << "Do you want to continue (Y/N)?" << endl;
cin >> again;
}while((again =='Y') || (again =='y'));
return 0;
}
double calculate_inflation (double yearAgo_price, double currentYear_price)
{
return ((currentYear_price-yearAgo_price)/ yearAgo_price);
}
while((again='Y') || (again='y'));
应该是
while((again=='Y') || (again=='y'));
您错误地将分配为比较运算符。这些在 C 和 C++ 中是不同的。
代码的效果是将Y
或y
分配给again
并返回新值。该字符不为零,因此转换为 true
.因此,返回true
,循环无休止。
编辑:
你怎么能用调试器自己找到它:
循环似乎是无穷无尽的,因此我们需要检查其条件变量。因此,在again
变量上放置一个监视,并在评估循环条件时看到它的变化。发现问题。
while ((again='Y') || (again='y')
不会做你认为它做的事情。您正在分配给again
变量。您要做的是使用 ==
运算符将again
与"Y"或"y"进行比较。