【问题标题】:C++ Array Input and Exit ValidationC++ 数组输入和退出验证
【发布时间】:2013-02-13 01:23:51
【问题描述】:

我不确定我输入无限量商品价格的方法有什么问题。但是,最大的问题是当我按零(它需要终止的方式)时,输入不会停止并且最终输出不会显示。任何更好的方法的方向都将不胜感激。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
const int MAX=8;
bool check=true;
double  totalPrice, discount, discountedPrice;
double *prices = new double[];

cout<<"Enter the price of your items.";
cout<<"Enter zero (0) when you have finished entering all the items.\n\n";

while(check==true)
{

for(int i=0;i<MAX;i++)
{

    cout<<"Enter the price of item "<<i<<": ";
    cin>>prices[i];

if(cin==0){

    check=false;


    break;

}
}

    if(prices==0)
    {
        check=false;
        break;

        for(int j=0; j<sizeof(prices);j++)
        {
            totalPrice+=prices[j];  
        }

        discount=totalPrice*.075;
        discountedPrice=totalPrice-discount;

        cout<<"The total price of your "<<sizeof(prices)<<"items is: $"<<totalPrice;
        cout<<"Discount of your "<<sizeof(prices)<<"is: $"<<discount;
        cout<<"\nThe discounted price of your "<<sizeof(prices)<<"is: $"<<discountedPrice;
    }
}

cin.get();
cin.get();

return 0;
}

【问题讨论】:

  • 使用矢量来调整自己的大小。
  • 数组似乎没问题,我检查过了。但是,我无法输入零来终止循环。我希望它尽可能简单。
  • 好吧,double *prices = new double[]; 甚至不是有效的语法。
  • 你有什么建议?这个数组需要处理十进制值,到目前为止它已经工作了。
  • 我已经推荐了std::vector。我不知道这是否是一个 MSVC 扩展,但一个向量可以很好地使用 push_back 或任何你喜欢的插入方法。

标签: c++ arrays visual-studio visual-c++ validation


【解决方案1】:

;应该是if(prices[i] == 0){ check = false; break; }

【讨论】:

  • 谢谢你,搞砸之后,你的逻辑运行良好。
【解决方案2】:
 cout<<"Enter the price of item "<<i<<": ";
    int temp;
    cin>>temp;
if(temp == 0){

    check=false;


    break;

}

应该解决这个问题,并且不会在价格数组中输入零。

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 1970-01-01
    • 2018-02-10
    • 2020-09-06
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2017-11-13
    相关资源
    最近更新 更多