【问题标题】:C++ Find the present value with user inputs and exponentC++ 使用用户输入和指数查找现值
【发布时间】:2020-03-18 13:42:35
【问题描述】:

我需要帮助来计算现值。用户将输入:支付金额(payamt)、期限(trm)和利率(intrte)。我在计算以下等式时遇到问题:

现值=支付金额*((1-(1+利息)^-期限)/利率)

这是我目前的代码:

#include <iostream>
using namespace std;

int main()

{
int trm = 0
    ;

double intrte = 0.0
    ;

float payamt = 0.0,
    presVal = 1
    ;

char
    response = '\0'
    ;

    cout << "Would you like to compute a present value? Enter Y for yes; N for no.";
    cin >> response;

    if (response != 'Y') {
        return 0;
    }

    cout << "\nPayment Amount: $";                  //payment in $ and cents for each year
    cin >> payamt;

    cout << "\nTerm (in years): ";                  //term number of years of payments
    cin >> trm;

    cout << "\nInterest Rate (between 0 and 100): ";//interest rate
    cin >> intrte;

    cout << "\n\nThe present value for a payment amount of $" << payamt
    << " and an interest rate of " << intrte
    << "%, and a term of " << trm
    << " years is $" << presVal
    << ".\n\n" << endl;

    presVal == payamt * (1 - ((1 + intrte), (-trm)))/intrte;
}

【问题讨论】:

  • 您能详细说明您遇到了什么问题吗?编译错误?运行时错误?错误信息是什么?
  • 在最后一行,您使用“==”比较 presVal,如果要将 te 公式分配给 presVal,则应使用“=”

标签: c++ algorithm exponent


【解决方案1】:

当您包含 cmath (#include &lt;cmath&gt;) 时,您可以使用 double pow(double base, double exponent) 函数将一个数字乘以另一个数字的幂。更多信息可以在这里找到:http://www.cplusplus.com/reference/cmath/pow/

你的公式变成了: presVal = payamt * (1 - pow(1+intrte, -trm))/intrte;

【讨论】:

  • 谢谢!我被指示不要使用除 iomanip 之外的任何其他头文件。你能建议吗?再次感谢你!非常感谢!
  • 您可以编写自己的 pow 函数,该函数实现了一个 for 循环,该循环迭代指数时间并将每次迭代的结果(初始化为 1)与基数相乘,并在结束时返回结果函数
  • “编写自己的 pow 函数”是什么意思?对不起,我是初学者:)
  • 我添加了 cmath 和您提供的公式。我仍然收到“1”作为现值。我认为这是因为它在变量中定义为“presVal = 1”。我需要创建一个“for”循环吗?谢谢!
  • 哇!非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 2014-08-03
  • 2020-03-07
  • 2014-11-29
  • 2020-07-10
  • 1970-01-01
  • 2016-07-24
相关资源
最近更新 更多