货币兑换计划

时间:2013-09-13 00:21:30

标签: c++

我正在研究一种货币转换器程序,它将英镑,先令和便士的旧系统转换为新系统,这是一种十进制磅。 100便士等于一磅。这是程序的代码

#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;

int calcNum(int pound, int shilling, int pence)
{
    pence = pound*240 + shilling*12 + pence;
    return pence;
}

int calcNew(int total_pence, double dec_pound)
{
    dec_pound = total_pence / 240;
    return dec_pound;
}

int main()
{

    int pence;
    int shilling;
    int pound;
    const int OLD_POUND = 240;
    const int OLD_SHILLING = 12;
    double total_pence;
    double dec_pound = 0;
    double deci_pound;

    cout << "Please Enter the Amount of old pounds: ";
    cin >> pound;
    cout << endl;
    if(cin.fail())
    {

        cout << "That's not a valid number\n";
        cout << "This program will terminate on any keypress!";
        _getch();
        exit(1);
    }
    cout << "Please Enter the Amount of old shillings: ";
    cin >> shilling;
    cout << endl;
    if(cin.fail())
    {
        cout << "That's not a valid number\n";
        cout << "This program will terminate on any keypress!";
        _getch();
        exit(1);
    }
    cout << "Please Enter the Amount of old pence: ";
    cin >> pence;
    cout << endl;
    if(cin.fail())
    {
        cout << "That's not a valid number\n";
        cout << "This program will terminate on any keypress!";
        _getch();
        exit(1);
    }
    total_pence = calcNum(pence, shilling, pound);
    deci_pound = calcNew(dec_pound, total_pence);
    cout << (5, "\n");
    cout << "The total amount in decimal pounds is: ";
    cout << setprecision(2) << "\x9c" << deci_pound;
    _getch();
    return 0;
}

但是当我运行这个程序时,我遇到了一些问题。无论数字输入是什么,它总是说0磅。为了确保最后的setprecision函数没有干扰代码,我最初在两个函数之后设置了一个带有_getch()的cout语句,以显示计算到的deci_pound的数量,并再次它出来是零。所以我的问题似乎是运行计算的函数中的某个地方。如果有人可以帮助我,我会非常感激。

2 个答案:

答案 0 :(得分:1)

您的calcNew(...)函数返回一个int,使其返回double。现在它转换为int,这涉及剥离小数。

在您的代码中,dec_pound设置为零,而您是deci_pound = calcNew(dec_pound, total_pence),它将0除以240 = 0.

答案 1 :(得分:0)

调用这两个函数时参数的顺序是错误的。您的函数声明并实现为:

int calcNum(int pound, int shilling, int pence);
int calcNew(int total_pence, double dec_pound);

然后你这样称呼他们:

total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);