我想计算物品的总价

时间:2017-09-23 10:57:22

标签: c++ class

我做错了什么?我想计算物品的总价格并显示它。 我在下面用for循环描述了我的问题。

#include<iostream.h>
#include<conio.h>

int T,N;

class item 
{
    int quantity;
    char name[100];
    float price;
    float Total;
    public:
    void get_data();
    void put_data();
    void calculate();
    void Total1();
};



void item::get_data()
{
    cout<<"Enter the name of the item "<<T+1<<" = ";
    cin>>name;
    cout<<"Enter the quantity= ";
    cin>>quantity;
    cout<<"Enter the price= ";
    cin>>price;

    cout<<"\n";

}

void item::put_data()
{
    cout<<"\n"<<name<<"\t\t   "<<quantity<<"\t\t   "<<price<<"\t\t\t"<<"SR";
}

我想计算物品的总价格,但是当我开始追踪程序时。它不是执行函数calculate()的for循环。这就是为什么我无法添加价格变量中存在的值而无法将其存储在变量Total中。

void item::calculate()
{
    for(T=0;T<N;T++)
    {
        Total=Total+price;
    }

}
void item::Total1()
{
    cout<<"\nTotal Amount= "<<Total;
}


void main()
{
    int N;
    clrscr();
    cout<<"Enter the Total number of item = ";
    cin>>N;
    item i[100];
    for(T=0;T<N;T++)
    {
        i[T].get_data();
    }

    cout<<"\nName of items";
    cout<<"\t\tQuantity ";
    cout<<"\titem price ";
    cout<<"\t\tGST ";

    for(T=0;T<N;T++)
    {
        i[T].put_data();
    }

        i[T].calculate();


        i[T].Total1();


        getch();

}

1 个答案:

答案 0 :(得分:1)

你在这里搞砸了很多东西。

一些可以帮助您解决问题的建议:

1。 避免在全球范围内做这样的事情:

int T,N;

而是直接在for语句中声明用作索引的变量:

for(int T=0; T<N; T++)

这会阻止你写出像

这样的错误陈述
i[T].calculate();

哪个完全疯了。循环后T没有任何有意义的值,好吧,它指向i []中的最后一个元素。但为什么最后一个元素能够总结所有项目?

  1. 准确考虑您的容器/包含关系
  2. 您使用int T;作为索引来迭代容器中的所有项目,但可能是什么意思

    void item::calculate()
    {
        for(T=0;T<N;T++)
        {
            Total=Total+price;
        }
    
    }
    

    这是item的成员函数,它应该如何能够总结存储在同一容器中的其他项的价格。您的物品不知道他们在同一个容器中有其他物品的事实。

    顺便说一句,如果你的追随者建议1编译器会提到你有错误。

    指导: 求和不能是项类的函数。您可以创建一个新的容器类,为您提供求和和其他东西,以及管理项目数组,或者您编写一个自由函数或作为第一步代码在main()中求和。

    最后一个看起来像(假设你公开价格):

    int total=0;
    for(T=0;T<N;T++)
    {
        total += i[T].price;
    }
    

    或(假设您提供价格的吸气剂)

    int total=0;
    for(T=0;T<N;T++)
    {
        total += i[T].price();
    }
    

    并使用c ++ 11,您可以使用基于范围的循环

    int total=0;
    for (const auto & item : items)
    {
        total += item.price();
    }
    
相关问题