startShare的if语句末尾的我的函数priceDifference没有返回计算的浮点数并将其显示在控制台中。我的其他功能正在正常运行,只是该功能正在变成香蕉,我不知道为什么。
例如,当我传递数字2105.11和1999.55时,它将返回1999.55 ???
#include <stdio.h>
void shareStart();
char askMe();
char askMe2();
char askMe3();
char askAgain();
int getShares();
int getMoney();
float getStartingInvestment();
float getSoldInvestment();
float getPrice();
float shareDivide(float, int);
float shareMultiply(float, int);
float priceDifference(float, float);
int main()
{
shareStart();
return 0;
}
void shareStart()
{
do {
if(askMe() == 'y') {
printf("You could buy: %f shares.\n", shareDivide(getPrice(), getMoney()));
} else if(askMe2() == 'y') {
printf("Shares cost: %f\n", shareMultiply(getPrice(), getShares()));
} else if(askMe3() == 'y') {
printf("Profit/Loss is: %f\n", priceDifference(getStartingInvestment(), getSoldInvestment()));
}
} while(askAgain() == 'y');
}
char askMe()
{
char ask;
printf("See how many shares to buy? 'y/n'\n");
scanf("%s", &ask);
return ask;
}
char askMe2()
{
char ask;
printf("See total cost of shares? 'y/n'\n");
scanf("%s", &ask);
return ask;
}
char askMe3()
{
char ask;
printf("See profit/loss difference between trades? 'y/n'\n");
scanf("%s", &ask);
return ask;
}
char askAgain()
{
char ask;
printf("Would you like to run the program again? 'y/n'\n");
scanf("%s", &ask);
return ask;
}
int getShares()
{
int ask;
printf("How many shares are you using?\n");
scanf("%d", &ask);
return ask;
}
int getMoney()
{
int money;
printf("How much money are you using?\n");
scanf("%d", &money);
return money;
}
float getStartingInvestment()
{
float money;
printf("How much money did your shares cost?\n");
scanf("%f", &money);
return money;
}
float getSoldInvestment()
{
float money;
printf("What did you sold your shares for?\n");
scanf("%f", &money);
return money;
}
float getPrice()
{
float price;
printf("Whats the price of a share?\n");
scanf("%f", &price);
return price;
}
float shareDivide(float price, int money)
{
return money / price;
}
float shareMultiply(float price, int shares)
{
return shares * price;
}
float priceDifference(float start, float sold)
{
return sold - start;
}
答案 0 :(得分:0)
我不知道它是如何工作的,但是注释中提到的答案是在所有Ask函数中将scanf函数格式说明符更改为“%c”。
Execution with "%s" specifier ~~ Execution with " %c" specifier
我在笔记本电脑的命令提示符中运行了带有指定符“%s”的程序,并且运行正常。某件事告诉我,在线编译器使它无法正常工作。
答案 1 :(得分:0)
%s
的{{1}}规范告诉它读取一系列非空白字符,并将它们以及一个终止的空字符存储在参数所指向的字符的空间中
当fscanf
用ask
定义时,传递char ask
会传递指向单个字符的空格的指针。这不足以容纳从输入中扫描的字符和终止的空字符。因此,您的程序名义上会尝试将一个空字符写入未为其分配的内存。这可能会以多种方式破坏您的程序。
将&ask
字符串更改为fscanf
告诉它读取单个字符并将其存储在参数所指向的位置,而不会终止为空字符。由于数据仅写入正确分配的空间,因此可以解决此问题。