为什么我的计算在我的程序中搞砸了?

Mic*_*el 2 c++

我不太确定我的代码在哪里导致导致错误计算的问题.当我运行该程序时,会出现以下警告:

C4305:'argument':从'double'截断到'float'.

税额(ta)和总成本(tc)似乎有问题,

Current Output:
Cost before Tax: $30.20
Tax Amount: $30.20     
Total Cost: $-107374144.00
ground beef is ex-sponged
Press any key to continue . .


What it **should** be:
Your item name:ground beef
Cost before Tax: $30.20
Tax Amount: $2.64
Total Cost: $32.84
ground beef is ex-sponged
Run Code Online (Sandbox Code Playgroud)
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<iomanip>
#include<string>

using namespace std;

class item
{
public:
    item(char* = " " ,float=0.0,int=0,float=0.0);
    ~item();
    void print();
    void calc(int);
private:
    char name[20];
    int quan;
    float cost, tp, cbt, tax, tc;
};
item::~item()
{
    cout << name << " is ex-sponged"<<endl;
    system("pause");
    }
item::item(char *w,float x, int y, float z)
{
    strcpy(name, w);
    cost = x;
    quan=y;
    tp = z;
    tax=cost*quan;
    tc=cbt+tax;
    cbt = cost*quan;
}
void item::print()
{
    cout << "Your item name:" << name << endl;
    cout << "Cost before Tax: $" << cbt << endl;
    cout << "Tax Amount: $" << tax << endl;
    cout << "Total Cost: $" << tc << endl;
}

void item::calc(int n)
{
    quan += n;
    cbt = cost*quan;
     tax = cbt*tp/100;
     tc = cbt + tax;
}

int main()
{
    item i("ground beef", 7.55, 4, 8.75);
    cout << setprecision(2) << showpoint << fixed;
    i.print();
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 7

在构造函数中,您在cbt初始化之前使用它:

tc=cbt+tax;
cbt = cost*quan;
Run Code Online (Sandbox Code Playgroud)

未初始化变量的值基本上是随机的.


无关的建议:

  • 使用std::string而不是C风格的字符串(char数组).

  • f在浮动文字上使用后缀来赋予它们类型float而不是double(从而删除警告):7.55f而不是7.55,0.0f(或0.f)而不是0.0等等.

  • 不要使用浮点格式,而是使用固定精度格式.货币贴现中的舍入误差和不准确性是不好的.

  • 在声明中命名参数,它用作自记录代码.

  • 通常,最好在构造函数中使用mem-initialiser-lists,而不是分配给构造函数体中的成员.这对于具有非平凡默认构造函数的类类型的成员尤其相关(对于不能默认初始化的成员而言,这是完全必需的).由于数据成员始终按类中的声明顺序初始化,因此您必须对它们进行重新排序.

我不知道定点格式,但是对于其他建议,你的代码看起来像这样:

class item
{
public:
    item(std::string name = " " , float cost = 0.0, int quant = 0, float tp = 0.0);
    ~item();
    void print();
    void calc(int);
private:
    std::string name;
    float cost;
    int quan;
    float tp, tax, cbt, tc;
};

item::~item()
{
    cout << name << " is ex-sponged" << endl;
    system("pause");
}

item::item(std::string name, float cost, int quant, float tp)
  : name(name),
    cost(cost),
    quan(quant),
    tp(tp),
    tax(cost * quant),
    cbt(cost * quant),
    tc(cbt + tax)
{
}

void item::print()
{
    cout << "Your item name:" << name << endl;
    cout << "Cost before Tax: $" << cbt << endl;
    cout << "Tax Amount: $" << tax << endl;
    cout << "Total Cost: $" << tc << endl;
}

void item::calc(int n)
{
    quan += n;
    cbt = cost*quan;
    tax = cbt*tp/100;
    tc = cbt + tax;
}
Run Code Online (Sandbox Code Playgroud)