0

我正在研究代数应用程序,这是代码

struct quotient
{
    int numerator;
    int denominator;
};

struct term
{
    struct quotient coefficient;
    char varname;
    struct quotient power;
};

struct function
{
    struct term* terms;
    char* operators;
    struct quotient coefficient;
    struct quotient power;
};

//Constructor Functions
struct quotient NewQuotient()
{
    struct quotient temp;
    printf("Enter the numerator\n");
    scanf("%d", &temp.numerator);
    printf("Enter the denominator\n");
    scanf("%d", &temp.denominator);
    return temp;
}

char NewVarname()
{
    char temp;
    printf("Enter the variable letter: \n");
    scanf("%c", &temp);
    return temp;
}

struct term NewTerm()
{
    //broken, won't let you enter a variable name, sets it to x by default until that's     resolved
    struct term temp;
    printf("Enter the coefficient: ");
    temp.coefficient = NewQuotient();
    printf("Enter the variable name: \n");
    temp.varname = NewVarname();
    temp.varname = 'x';
    printf("Enter the power: ");
    temp.power = NewQuotient();
    return temp;
}

void NewFunction(struct function* func, int size)
{
    //so far so good
    unsigned i;
    func->terms = (struct term*)calloc(size, sizeof(struct term));
    //loop to initialize each term
    for(i = 0; i < size; i++)
    {
        func->terms[i] = NewTerm();
    }
    return;
}

int main(){
    struct function fofx;
    NewFunction(&fofx, 2);
    DisplayFunction(&fofx, 2);
    DeleteFunction(&fofx);

    return 0;
}

这是输出:

输入分子:
1
输入分母:
2
输入分子:
3
输入分母:
4
....

等等,直到循环结束。

NewTerm 中的一半语句似乎根本没有执行,但程序似乎成功分配并初始化了一个新函数。非常感谢任何帮助,我对此感到非常困惑。我没有包括显示和删除功能,它们工作正常,但如果它们有帮助,我可以在这里添加它们。

4

3 回答 3

1

使用时scanf,您通常希望获取 Return 键以及数字。

你有:

scanf("%d", &temp.numerator);

你真的想要:

scanf("%d\n", &temp.numerator);
于 2012-07-21T00:39:08.003 回答
1

您没有为 calloc 提供正确的大小,应该是sizeof (struct term)而不是sizeof (int). struct term这可能是问题所在,具体取决于size.

关于NewTerm不被调用,那可能是因为你没有调用它。

于 2012-07-19T03:14:12.710 回答
0

您还应该使用验证来确保只输入数字,否则您会得到古怪的结果。

于 2012-07-21T01:39:07.950 回答