我需要有关以下代码的公式的帮助:
#include <stdio.h>
void main()
{
int MAGNUM, AK47, Knife, Axe, total;
char choice, choice2, confirm;
MAGNUM = 75;
AK47 = 150;
Knife = 40;
Axe = 20;
printf("Welcome to weapon store.\n");
printf("Over here, we sell cheap weaponry you may be interested in.\n");
printf("Currently, this is what we have for sale:\n\n\n");
printf("(A) .44 MAGNUM\n");
printf("(B) AK-47\n");
printf("(C) Laredo Bowie knife\n");
printf("(D) Tomahawk axe\n\n\n");
printf("Pick one to buy, just type the letter in caps of the item and press enter.\n");
printf("ITEM SELECTED:");
scanf("%c", &choice); //First input//
if (choice == 'A')
{
printf("That will be $%d.\n", MAGNUM);
}
if (choice == 'B')
{
printf("That will be $%d.\n", AK47);
}
if (choice == 'C')
{
printf("That will be $%d.\n", Knife);
}
if (choice == 'D')
{
printf("That will be $%d.\n", Axe);
}
printf("Do you want to buy anything else?<Y//N>\n"); //Second input//
scanf(" %c", &choice2);
if (choice2 == 'Y')
{
printf("What else do you want to buy:"); //Third input//
scanf(" %c", &confirm);
if (confirm == 'A')
{
printf("That will be $%d.\n ", MAGNUM);
}
else if (confirm == 'B')
{
printf("That will be $%d.\n", AK47);
}
else if (confirm == 'C')
{
printf("That will be $%d.\n", Knife);
}
else if (confirm == 'D')
{
printf("That will be $%d.\n", Axe);
}
total = choice + confirm; //Need help with formula here. total equals first input + third input//
printf("Total cost is $%d. Thank you.\n", total);
}
else
{
printf("Thank you for shopping with us.\n");
}
}
调试时,如果将它们加在一起,它将不会显示输入1和3的正确值。
例如,如果我分别为输入1和3选择D然后再选择D,那么我应该总共获得40美元,但我获得了不同的$ 136值。
这可能是我目前缺乏C知识,因为我两天前才开始。这段代码只是我对基础知识的一个测试基础,比如if else语句等,所以如果代码中的内容可能会冒犯任何人,我会道歉。
答案 0 :(得分:0)
您要添加的是字符值而不是价格。
68是'D'被解释为整数。 68 + 68 = 136。
我会在if语句中添加价格,例如
if (choice == 'D')
{
printf("That will be $%d.\n", Axe);
total=total+Axe;
}
答案 1 :(得分:0)
(代表OP发布)。
将C ++作为标题是我的错误。没有意识到这一点。之前也不知道字符值。
初始化一个grandtotal = total1 + total2,其中total1表示输入1的选择结果的值,而total2表示输入3的选择结果的值,解决了问题。