[问题3]:考虑在0和1之间的所有分母不大于N的最简分数。下面是N=5时的情况:
0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 l/1
程序对于一个给定的整数N(1<=N<=100),按从小到大的顺序打印出这些
分数。还应打印出它们的总数。在每个分数后面打印一个制表符,使他们在显示的时
候一行不会很长。
要求:当N<1或N>100时,程序应判错。
举例:
enter the maximum demominator:5
0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 l/1
there are 11 fractions.
程序如下:
type denominator=array[1..2] of byte;
var a: array[1..10000] of denominator;
n,num:word;
procedure init;
begin
repeat
write(‘enter the maximum denominator:’);
readln(n);
if not(n in[1..100]) then writeln(‘input error!);
until n in [1..100];
num:=0;
end;
procedure calc;
var i,j;word;
mid:denominator;
procedure add(x,y:word);
var k:word;
begin
for k:=2 to y do
if(x mod k=0)and(y mod k=0)then exit;
inc(num);
a[num,1]:=x;
a[num,2]:=y;
end;
begin
for i:=2 to n do
for j:=1 to i-1 do
add(i,j);
for i:=1 to num do
for j:i+1 to num do
{ if(a[i,1]*a[j,2]<a[i,2]*a[j,1])then 或if (a[i,2]/a[i,1]>a[j,2]/a[j,1]) then }
begin
mid:=a[i];
a[i]:=a[j];
a[j]:=mid;
end;
end;
procedure print;
var i:word;
begin
write(‘0/1’,#9);
for i:=1 to num do
write(a[i,2],’/’,a[i,1],#9);
writeln(‘1/1’,#9);
writeln(‘there were’,num+2,’fractions.’);
end;
begin
init;
calc;
print;
end.