而真正的循环功能

时间:2017-06-03 18:40:53

标签: c++ c while-loop

据我了解,while循环可以这样做:

while (true) {
    // run this code
    if (condition satisfies)
        break; // return;
}

所以我接受了它并且我在下面输入了以下主要功能,我的问题是当我在满足条件(5或更多)后放入printf语句时,它会停止并且不会显示任何内容,如果我除了它工作的break语句之外什么都没有,它循环通过5个不同的客户!我错过了关于while true循环的任何内容,还是它的工作方式?

int main ()
{
    displayMenu();
    while (true)
    {
        int gasType,gallonsAmount,carWashOption,customerAmount ;
        float gasPrices[SIZE]={2.99,3.099,3.199,3.299}, washPrices[SIZE]=
        {3.50,3.00,3.00,2.50}, perGallonRate,perWashRate,total;
        float totalSum,totalGallonSum;
        gasType = getGasType();
        gallonsAmount = getGallons();
        carWashOption = getCarWash();
        perGallonRate = getGallonRate(gasPrices, gasType);
        if (carWashOption == 'Y')
        {
            perWashRate = getWashRate( washPrices, gasType );
            total = calcAmount(gallonsAmount, perGallonRate, perWashRate,&totalSum, &totalGallonSum);
        }
        else 
        {
            perWashRate = 0;
            total = calcAmount(gallonsAmount, perGallonRate, perWashRate,&totalSum, &totalGallonSum);
        }
        customerAmount++;// once we reach a total of 5 customers(Assume its the end of the day), the loop will break and give me a summary.
        if (customerAmount >= 5)
            printf("totalSum: %.2f ", totalSum ,totalGallonSum);
            break;
    }   

    return 0;
}

1 个答案:

答案 0 :(得分:6)

 if (customerAmount >= 5)
    printf("totalSum: %.2f ", totalSum , totalGallonSum  );
    break;

break不属于if。所以第一次循环结束。 使用大括号。

 if (customerAmount >= 5)
 {
    printf("totalSum: %.2f ", totalSum , totalGallonSum  );
    break;
  }