【问题标题】:How to loop a switch statement until desired number is found?如何循环 switch 语句直到找到所需的数字?
【发布时间】:2018-06-23 03:58:58
【问题描述】:
cout<<"========================================="<<endl<<endl;
 cout<<"The amount you need to pay is RM "<<total<<endl;
 cout<<"=========================================="<<endl<<endl;
 cout<<"You can pay using ($0.10 [1] $0.20 [2] $0.50 [3] $1 [4] $5 [5] $10 [6] $20 [7] $50 [8] )"<<endl;



 cin>>choice2;


 switch(choice2){
case 1:
    total = total - 0.10;
    break;

case 2:
    total = total - 0.20;
    break;

case 3:
    total = total - 0.50;
    break;

case 4:
    total = total - 1;
    break;

case 5:
    total = total - 5;
    break;

case 6:
    total = total - 10;
    break;

case 7:
    total = total - 20;
    break;

case 8:
    total = total - 50;
    break;

default:
    cout<<"inavalid!"<<endl;

 }

if(total > 0){

    cout<<"you still need to pay "<<total<<endl;
    cin>>choice2;
}

额外信息:我的总价是 5 美元

我试图让它循环直到支付总金额,假设我选择案例 4,即 1 美元。假设让我插入我应该支付的剩余金额,即 4 美元,但在我插入另一个 switch case 选项后程序结束。

这部分,不应该循环到我的总数为0吗?

if(total > 0){

    cout<<"you still need to pay "<<total<<endl;
    cin>>choice2;
}

提前感谢您的帮助,如果有的话,我也很高兴学习编写这个程序的任何更短的方法,还有我可以在这个程序中实现数组吗?

【问题讨论】:

    标签: c++ loops switch-statement


    【解决方案1】:

    不,switchif 都不会导致您的程序循环。

    你可能正在寻找类似的东西

    while(total > 0)
    {
        cin>>choice2;
    
       switch(choice2){
        // left out for clarity
       }
    
    
        if(total > 0){
            cout<<"you still need to pay "<<total<<endl;
            //Instead of getting the input in 2 different locations, just get it again at the start of the next loop.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-23
      • 2015-01-10
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 2020-04-13
      • 1970-01-01
      相关资源
      最近更新 更多