【发布时间】:2012-07-18 04:30:50
【问题描述】:
我正在开发代数应用程序,这是代码
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 中的一半语句似乎根本没有执行,但程序似乎成功分配并初始化了一个新函数。非常感谢任何帮助,我对此感到非常困惑。我没有包含显示和删除功能,它们工作正常,但如果它们有帮助,我可以在此处添加它们。
【问题讨论】:
-
您没有发布 NewQuotient 的代码。您应该发布整个相关代码。
-
抱歉,我以为我在里面,现在已经添加了。
-
缺少 struct term 的代码。您能否发布所有相关代码,以便我可以编译/尝试它。
-
我添加了结构和主要功能,我想这就是一切。
标签: c pointers structure dynamic-allocation