如何在char中使用For循环?

时间:2015-04-25 00:04:17

标签: c loops for-loop char

  • 使用for循环。我想让用户输入他们想要订购的柠檬水量。然后我的程序将计算税额,小计和总计。之后应该让他们继续进入' y'或者' n'。

  • 编译这些代码时。我得到的只是空白。我的代码出了什么问题?

所以我做了一些改变。但是,如果我输入' n' n,我就不知道怎么让它停止。如果他们要求继续。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

void main()
{
    int NumCups;
    float SubTot, Tot = 0, Tax;
    char more;

    printf("Enter the number of cups:");
    scanf("%d", &NumCups);
    SubTot = NumCups*1.29;
    Tax = SubTot*0.0825;
    Tot = SubTot + Tax;

    printf("Subtotal:%0.2f\nTax:%0.2f\nTotal:%0.2f\n", SubTot, Tax, Tot);
    fflush(stdin);
    printf("Thank you.\nWould you like to order more lemonade?\n");

    for (; scanf("%c", &more);)
    {
        printf("Enter the number of cups:");
        scanf("%d", &NumCups);

        SubTot = NumCups*1.29;
        Tax = SubTot*0.0825;
        Tot += SubTot + Tax;
        fflush(stdin);
        printf("Subtotal:%0.2f\nTax:%0.2f\nTotal:%0.2f\n", SubTot, Tax, Tot);
        printf("Thank you.\nWould you like to order more lemonade?\n");
    }
    system("pause");
}

2 个答案:

答案 0 :(得分:1)

试试这个:

 for (; scanf("%c", &more)&&more=='y';)

此更改只允许您在使用y字符时继续。

答案 1 :(得分:0)

do {
    printf("Enter the number of cups:");
    scanf("%d", &NumCups);

    SubTot = NumCups*1.29;
    Tax = SubTot*0.0825;
    Tot += SubTot + Tax;
    fflush(stdin);
    printf("Subtotal:%0.2f\nTax:%0.2f\nTotal:%0.2f\n", SubTot, Tax, Tot);
    printf("Thank you.\nWould you like to order more lemonade?\n");
} while(1 == scanf(" %c", &more) && 'y' == more);