2

我正在开发一个货币转换器程序,将英镑、先令和便士的旧系统转换为他们的新系统,这是一种十进制英镑。其中 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,然后再一次,结果为零。所以我的问题似乎出在运行计算的函数中。如果有人可以帮助我,我将不胜感激。

4

2 回答 2

1

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

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

于 2013-09-13T00:27:26.560 回答
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);
于 2013-09-13T13:30:11.370 回答