gpt4 book ai didi

C 使用存储在 char 中的变量

转载 作者:行者123 更新时间:2023-11-30 17:08:44 25 4
gpt4 key购买 nike

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;
}

大家好,正如您所看到的,我正在尝试让程序告诉客户他购买的价格(价格 = 答案 * 升)。作为回答,他输入了一个存储的字母(RSD)。它不是应该使用我将其声明为浮点变量的值吗?因为当我回答 * 升时,我得到了错误的值,即:客户选择 100 升,而 S,答案应该是 750 (100 * 7.5),但事实并非如此。

我对 C 或任何其他编程语言都很陌生。感谢您的帮助。

最佳答案

你不能这样做... 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;
}

关于C 使用存储在 char 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33553213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com