这里是我当前代码的一部分(仍然不完整)。我试图将成本金额分配给* costPtr。但在分配之后,我在主函数中测试结果,看看我是否得到了我选择的正确值,结果似乎是0.00001而不是指定的值(299.9或349.99或999.99)。怎么了?我找不到答案。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
void DisplayApps(char *selectionPtr);
void SetCost(char selection, double *costPtr);
//void PaymentOptions(double *depositPtr, double cost);
//int Compare(double deposit, double choiceCost);
//void Pay(double *depositPtr, double choiceCost);
//void GetChanged(double *depositPtr, double choiceCost);
//void DoItAgain(char *quitPtr);
int main()
{
char selection;
char *selectionPtr;
//double choiceCost;
double *costPtr;
//double *depositPtr;
//char *quitPtr;
printf("Welcome to the App Store\n");
printf("***************************\n\n");
DisplayApps(&selectionPtr);
selection = selectionPtr;
printf("Your choice %c\n", selection);
SetCost(selection, &costPtr);
printf("The cost of this item is %fl\n", costPtr);
return 0;
}
void DisplayApps(char *selectionPtr)
{
printf("-------------------------\n");
printf("HERE ARE THE SLECTIONS\n");
printf("C -- Clown Punching $299.99\n");
printf("V -- Virtual Snow Globe $349.99\n");
printf("R -- Remote PC $999.99\n");
printf("G -- Grocery List Helper $2.99\n");
printf("M -- Mobile Cam Viewer $89.99\n");
printf("\n");
printf("Please enter a selection: ", *selectionPtr);
scanf(" %c", &*selectionPtr);
}
void SetCost(char selection, double *costPtr)
{
double c = 299.99;
double v = 349.99;
double r = 999.99;
double g = 2.99;
double m = 89.99;
if (selection == "C" || selection == "c")
{
*costPtr = c;
}
else if (selection == "V" || selection == "v")
{
*costPtr = v;
}
else if (selection == "R" || selection == "r")
{
*costPtr = r;
}
else if (selection == "G" || selection == "g")
{
*costPtr = g;
}
else if (selection == "M" || selection == "m")
{
*costPtr = m;
}
}
答案 0 :(得分:2)
您的程序格式错误且使用未定义的行为,因为您在SetCost
参数上使用double**
呼叫double*
。
您最好在cost
中将double
变量声明为正常main
:
int main()
{
// ...
double cost;
// ...
SetCost(selection, &cost);
printf("The cost of this item is %fl\n", cost);
// ...
}
答案 1 :(得分:0)
在main
中,声明double cost
并将&cost
传递给SetCost
。然后打印cost
。如果启用了警告,那么您的编译器可能会遇到问题。例如,当您正在寻找double **
时,您已将SetCost
传递给double *
。