题目原文链接:点击打开链接
翻译题目要求:
程序输入为两行:均为一个多项式,按格式K N1 An1 N2 An2......Nk Ank,K代表的是多项式的非零项数,范围闭区间是[1,10],N1到Nk的范围区间是 1<= Nk <= ......<= N1 <= 1000;
Nk是指数,Ank是系数,将两个多项式相乘,结果为一个新的多项式。
举例:
输入(两个多项式均有两项):
2 1 2.4 0 3.2
2 2 1.5 1 0.5
输出为一个三项的多项式:
3 3 3.6 2 6.0 1 1.6
设计代码如下:
// Pattest 1009,多项式的乘法计算
#include <stdio.h>
#include <string.h>
//多项式存储结构定义
typedef struct
{
int exponents;
float coeffients;
}Polynomial,*pPolynomial;
// 多项式因子数目
int poly_size1 = 0;
int poly_size2 = 0;
int poly_size3 = 0;
int max_polyindex = 0;
// 乘子与结果多项式
Polynomial poly1[10];
Polynomial poly2[10];
Polynomial polyResult[20];
//从输入中提取多项式信息
int parse(char* input, pPolynomial poly, int& size)
{
int exponent = 0;
float coeffient = 0.0;
char buffer[1024] = {0};
char* p = NULL;
char* q = NULL;
sscanf( input, "%d %s", &size, buffer );
p = input;
for ( int i = 0; i < size; i++ )
{
memset(buffer, 0, sizeof(buffer) );
while( *p != ' ') p++;
q = p + 1 ;
while( *q != ' ') q++;
q++;
while( *q != ' ')
{
q++;
if ( (q - input) == strlen(input) )//the end case
break;
}
q--;
strncpy( buffer, p, q-p+1 );
sscanf( buffer, "%d %f",&exponent, &coeffient );
poly[i].coeffients = coeffient;
poly[i].exponents = exponent;
p = q+1;
}
return 1;
}
// 接收输入
int pickup()
{
char input[1024] = {0};
printf("Please input the first polynomials:\n");
scanf("%[^\n]",input);
parse(input, poly1, poly_size1);
memset(input, 0, sizeof(input));
printf("Please input the second polynomials:\n");
getchar();
scanf("%[^\n]",input);
parse(input, poly2, poly_size2);
return 1;
}
// 计算多项式,合并
int calc()
{
memset( &polyResult, 0, sizeof(polyResult) );
for ( int i = 0; i < poly_size1; i++ )
{
int expo1 = poly1[i].exponents;
float coef1 = poly1[i].coeffients;
for ( int j = 0; j < poly_size2; j++ )
{
int expo2 = poly2[j].exponents;
float coef2 = poly2[j].coeffients;
int new_exponent = expo1 + expo2;
// 保存多项式最高项次
if ( new_exponent > max_polyindex )
{
max_polyindex = new_exponent;
}
if ( polyResult[ new_exponent ].coeffients > 0.01 )
{
polyResult[ new_exponent ].coeffients += coef1*coef2;
}
else
{
// 保存多项式相乘结果的实际多项数
poly_size3++;
polyResult[ new_exponent ].coeffients = coef1*coef2;
}
polyResult[ new_exponent ].exponents = expo1+expo2;
}
}
return 1;
}
// 输出结果
int print()
{
char szResult[200] = {0};
sprintf_s(szResult,"%d",poly_size3);
for ( int i = max_polyindex; i >= 0; i-- )
{
if ( polyResult[i].coeffients > 0.01 )
{
char buffer[20] = {0};
sprintf_s(buffer, " %d %.1f", polyResult[i].exponents, polyResult[i].coeffients );
strcat(szResult, buffer);
}
}
printf( "%s\n", szResult );
return 1;
}
// 输入多项式并计算相乘之后的结果,输出
int main()
{
pickup();
calc();
print();
return 0;
}
另有更好的思路,正在考虑中,欢迎大伙提供思路。