C使用存储在char中的变量

时间:2015-11-05 19:32:02

标签: c char

int main()
{
    float S = 7.5, R = 5.85, D = 5.95, liters, price;
    char answer;
    printf("Choose one of the following fuels or X to quit:\nS - gas 98 \nR - gas 95\nD - diesel fuel\n");
    scanf("%c", &answer);
    switch (answer)
    {
        case 'S': case 's':
            printf("You selected to fuel with gas 98\n");
            break;
        case 'R': case 'r':
            printf("You selected to fuel with gas 95\n");
            break;
        case 'D': case 'd':
            printf("You selected to fuel with disel fuel\n");
            break;
        case 'X': case 'x':
            printf("Thank you.\n");
            break;
}
    printf("The price list is:\ngas98 - 7.5 NIS\ngas98 - 5.85 NIS\ndiesel - 5.95 NIS\n");
    printf("How much liters would you like to fuel?\n");
    scanf("%f", &liters);
    price = answer * liters;
    printf("You choose to fuel %0.0f\nThe price is:%0.0f\n", liters, price);
    return 0;
}

大家好, 正如你所看到的那样,我试图让程序告诉顾客他购买的价格(price = answer * liters)。作为回答,他输入了一封存储的信件(RSD)。是不是应该使用我声明为浮点变量的值? 因为当我回答*升时,我得到一个错误的值,即:客户选择100升,而S,答案应该是750(100 * 7.5),但它不是。

我真的很喜欢c或任何其他编程语言。 谢谢你的帮助。

4 个答案:

答案 0 :(得分:0)

字符不是变量。您必须在案例中设置标记或其他内容。

float SelectedThing;

case 'S':
-----
SelectedThing = S;

price = SelectedThing * liters;

答案 1 :(得分:0)

你不能这样做...... answer包含一个不能用来简单地用名称表示另一个变量的值。您可以做的是像这样在交换机中分配基本价格,并进一步使用它来计算最终价格:

int main()
{
    float liters, price, basePrice;
    char answer;
    printf("Choose one of the following fuels or X to quit:\nS - gas 98 \nR - gas 95\nD - diesel fuel\n");
    scanf("%c", &answer);
    switch (answer)
    {
        case 'S': case 's':
            printf("You selected to fuel with gas 98\n");
            basePrice = 7.5;
            break;
        case 'R': case 'r':
            printf("You selected to fuel with gas 95\n");
            basePrice = 5.85;
            break;
        case 'D': case 'd':
            printf("You selected to fuel with disel fuel\n");
            basePrice = 5.95;
            break;
        case 'X': case 'x':
            printf("Thank you.\n");
            return 0;
    }
    printf("The price list is:\ngas98 - 7.5 NIS\ngas98 - 5.85 NIS\ndiesel - 5.95 NIS\n");
    printf("How much liters would you like to fuel?\n");
    scanf("%f", &liters);
    price = basePrice * liters;
    printf("You choose to fuel %0.0f\nThe price is:%0.0f\n", liters, price);
    return 0;
}

答案 2 :(得分:0)

answer不是float,而是char,其中包含'S'之类的字母。

还有一个变量S,但这与answer无关。实现此目的的一种方法是在您的case声明中决定使用哪个价格并将其保存在float中,可能是selectedPrice。然后乘以升数。

请注意,char值可以视为数字。例如,您可以乘以'S' * 10,这是有效的,因为C会将char视为与其ASCII值等效。 'S'在ASCII中是83,因此输入“S”然后选择10升将得到830.不是你想要的。

答案 3 :(得分:0)

在您的陈述price = answer * liters;中,您将char乘以float,这不会产生您的期望。您需要做的是在switch语句中指定一个{ {1}}根据选择

变量S,R或D的值
float