gpt4 book ai didi

c - 为什么我的 float 函数没有按预期工作?

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

我的函数priceDifference在startShare的if语句最后没有返回计算出的 float 并将其显示在控制台中。我的其他功能运行正常,只是那个功能出了问题,我不知道为什么。

例如,当我传递数字 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;
}

最佳答案

fscanf 的 %s 规范告诉它读取一系列非空白字符并将它们与终止空字符一起存储在空格中对于参数指向的字符。

当用 char Ask 定义 ask 时,传递 &ask 会传递一个指向单个字符空间的指针。这不足以容纳从输入扫描的字符和终止空字符。因此,您的程序名义上会尝试将空字符写入未为其分配的内存。这可能会以多种方式破坏您的程序。

fscanf 字符串更改为 %c 告诉它读取单个字符并将其存储在参数指向的位置,而无需终止空字符。这解决了问题,因为数据仅写入正确分配的空间。

关于c - 为什么我的 float 函数没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55319127/

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