首页上一页 1 下一页尾页 1 条记录 1/1页
C语言282例中的第61页到62页
发表在C语言图书答疑
2015-05-10
是否精华
是
否
版块置顶:
是
否
#include<stdio.h>
#include<stdlib.h>
//haha
void result(int a,int b,int c,int * x2,int * y2)
{
int x[100],y[100],z[100];
int i,j,d,t,gcd;
x[0] = 0;
y[0] = 1;
for(i=0; i < 100; ++i)
{
z[i] = a / b;
d = a % b;
a = b;
b = d;
if(d == 0)
{
gcd = a;
break;
}
if(i == 0)
{
x[1] = 1;
y[1] = z[0];
}
else
{
x[i+1] = z[i]*x[i] + x[i-1];
y[i+1] = z[i]*y[i] + y[i-1];
}
}
for(t =-1,j = 1; j < i; ++j)
t = -t;
*x2 = -t * x[i];
*y2 = t * y[i];
if(c % gcd != 0)
{
printf("无解!\n");
exit(0);
}
t = c / gcd;
*x2 = *x2 * t;
*y2 = *y2 * t;
}
void test(int a,int b,int c,int x,int y)
{
if(a*x + b*y ==c)
printf("correct!\n");
else
printf("error!\n");
}
int main(void)
{
int a,b,c,x2,y2;
x2 = 0;
y2 = 0;
printf("输入a,b,c:\n");
scanf("%d%d%d",&a,&b,&c);
result(a,b,c,&x2,&y2);
test(a,b,c,x2,y2);
printf("x = %d,y = %d\n",x2,y2);
return 0;
}
这个程序有问题,比如说我输入:2 1 4 运行的结果如下:
输入a,b,c:
2 1 4
error!
x = 0,y = -4
很显眼结果是错的呀,因为2*x + 1*y = 4这个方程很显然是有整数解的呀,比如x = 1,y = 2
求解释呀!!!
#include<stdlib.h>
//haha
void result(int a,int b,int c,int * x2,int * y2)
{
int x[100],y[100],z[100];
int i,j,d,t,gcd;
x[0] = 0;
y[0] = 1;
for(i=0; i < 100; ++i)
{
z[i] = a / b;
d = a % b;
a = b;
b = d;
if(d == 0)
{
gcd = a;
break;
}
if(i == 0)
{
x[1] = 1;
y[1] = z[0];
}
else
{
x[i+1] = z[i]*x[i] + x[i-1];
y[i+1] = z[i]*y[i] + y[i-1];
}
}
for(t =-1,j = 1; j < i; ++j)
t = -t;
*x2 = -t * x[i];
*y2 = t * y[i];
if(c % gcd != 0)
{
printf("无解!\n");
exit(0);
}
t = c / gcd;
*x2 = *x2 * t;
*y2 = *y2 * t;
}
void test(int a,int b,int c,int x,int y)
{
if(a*x + b*y ==c)
printf("correct!\n");
else
printf("error!\n");
}
int main(void)
{
int a,b,c,x2,y2;
x2 = 0;
y2 = 0;
printf("输入a,b,c:\n");
scanf("%d%d%d",&a,&b,&c);
result(a,b,c,&x2,&y2);
test(a,b,c,x2,y2);
printf("x = %d,y = %d\n",x2,y2);
return 0;
}
这个程序有问题,比如说我输入:2 1 4 运行的结果如下:
输入a,b,c:
2 1 4
error!
x = 0,y = -4
很显眼结果是错的呀,因为2*x + 1*y = 4这个方程很显然是有整数解的呀,比如x = 1,y = 2
求解释呀!!!