我需要以下代码的公式帮助:
#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。
可能是因为我现在才刚开始2天,所以目前我缺乏C知识。这段代码只是我了解基础知识(例如,if语句等)的试验场,因此,我对代码中的内容可能对任何人都感到冒犯表示歉意。
最佳答案
您要添加字符值而不是价格。
68被解释为整数的“ D”。 68 + 68 = 136。
我会在您的if语句中添加价格,例如
if (choice == 'D')
{
printf("That will be $%d.\n", Axe);
total=total+Axe;
}