我在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;
}

最佳答案

%sfscanf规范告诉它读取一系列非空白字符,并将它们以及一个终止的空字符存储在参数所指向的字符的空间中。

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

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

10-07 23:01