衡量c ++

时间:2016-07-09 20:10:36

标签: c++

编写一个程序来衡量过去一年的通货膨胀率。该计划要求一年前和今天的物品(如热狗或1克拉钻石)的价格。它将通货膨胀率估计为价格差异除以一年前的价格。您的程序应允许用户按照用户的意愿重复此计算。定义一个计算通货膨胀率的函数。通货膨胀率应为double类型的值,给出百分比,例如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);
   }

2 个答案:

答案 0 :(得分:1)

while((again='Y') || (again='y'));

应该是

while((again=='Y') || (again=='y'));

您错误地指定了比较运算符。这些在C和C ++中有所不同。

您的代码的效果是Yy已分配给again,并返回新值。该char不为零,因此转换为true。因此,返回true,循环变为无穷无尽。

修改

如何使用调试器自行找到它:

循环似乎是无穷无尽的,因此我们需要检查其条件变量。因此,请在again变量上进行监视,并在评估循环条件时查看它。发现问题。

答案 1 :(得分:1)

while ((again='Y') || (again='y')没有按照您的想法行事。您正在分配again变量。 您要做的是使用==运算符 again与'Y'或'y'进行比较。