如何循环执行switch语句,直到找到所需的数字?

时间:2018-06-23 03:58:59

标签: c++ loops switch-statement

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,但在我插入另一个切换用例选项之后,程序结束。

这部分,是不是应该在我的总数为0之前循环播放?

if(total > 0){

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

在此先感谢您的帮助,如果有的话,我也很高兴学习编写此程序的任何更短方法,无论如何,我还能在该程序中实现数组吗?

1 个答案:

答案 0 :(得分: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.
    }
}