【发布时间】:2015-01-01 22:50:17
【问题描述】:
我正在使用数组实现多项式。这是问题陈述:
编写一个菜单驱动程序,将多项式表示为使用数组的数据结构。编写函数来加、减和乘两个多项式;将多项式与常数相乘,求多项式是否为“零多项式”,返回多项式的次数。假设每次运算后都会创建一个新多项式。您将如何输入和输出多项式?
我已经创建了输入和输出函数。但是我的 do while 循环运行了两次。帮助我找出原因。
do-while 循环
do{
print_menu();
scanf("%c",&ch);
printf("\nch = %c\n",ch);
switch(ch){
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
}while(ch != 'q');
return 0;
}
print_menu() 函数
void print_menu()
{
printf("\n1. Create a new polynomial.");
printf("\n2. Print polynomial.");
printf("\nq. Exit");
printf("\nEnter Choice:");
}
create_poly() 函数
void create_poly(int poly[][2], int termpool[][2], int *next_poly)
{
int beg = poly[*next_poly][0];
int end, size, i, j;
printf("Enter size of the polynomial:");
scanf("%d",&size);
poly[*next_poly][1] = beg + size - 1;
end = poly[*next_poly][1];
printf("Enter terms of the polynomial(coeff then exponent):\n");
for(i=beg; i<=end; i++){
for(j=0; j<2; j++){
scanf("%d ",&termpool[i][j]);
}
}
poly[++(*next_poly)][0] = end + 1;
}
The print_poly()函数
void print_poly(int poly[][2],int termpool[][2],int *next_poly)
{
int pos,beg,end;
int i;
printf("Enter position of the polynomial:");
scanf("%d",&pos);
if(pos-1 > *next_poly){
printf("Invalid position.");
return;
}
beg = poly[pos-1][0];
end = poly[pos-1][1];
for(i=beg; i<=end; i++){
printf(" %dx^%d +",termpool[i][0],termpool[i][1]);
}
printf("\b = 0");
}
这是一个示例输出:
1. 创建一个新的多项式。 2. 打印多项式。 问。出口 输入选择:1 ch = 1 输入多项式的大小:2 输入多项式的项(系数然后指数): 2 4 6 7 1. 创建一个新的多项式。 2. 打印多项式。 问。出口 输入选择: ch = 无效的选择。 1. 创建一个新的多项式。 2. 打印多项式。 问。出口 输入选择:q ch = q尝试刷新stdin... 问题仍然存在。在每一步打印ch的值,我认为它是一个空格。空白从哪里来?
abnormal behavior of scanf 的答案也回答了这个问题。
【问题讨论】:
-
你应该阅读你正在使用的每个函数的文档,特别是scanf(3)。您应该测试
scanf的结果。您应该使用所有警告和调试信息 (gcc -Wall -Wextra -g) 进行编译。您应该学习如何使用调试器 (gdb)。另外,编辑您的问题以改进它。它缺少Linux标签! -
@BasileStarynkevitch:我不同意标签建议。如果它应该是可移植的(没有迹象表明它不应该),那么 linux-tag 将是错误的。
-
我想你会发现 this question 信息丰富,顺便说一句。
-
这一行:scanf("%d",&pos);有两个问题 1) 需要检查 scanf() 的返回值以确保实际输入/设置目标参数。 2) scanf() 不会在格式参数中没有特定编码的情况下消耗空白。建议格式参数为:“%d”,以便使用前导空格,包括任何换行符