我重新制作了我的代码,看起来像这样:
{$APPTYPE CONSOLE}
type vector = array[1..100] of integer;
var a:vector;
var i,n:integer;
var br:integer;
var sum,average:real;
begin
write('Enter number elements of the array: '); readln(n);
for i:=1 to n do
begin
write('Enter ' ,i, ' element: '); readln(a[i]);
end;
br:=0;
sum:=0;
for i:=1 to n do
if not(odd(a[i])) and (odd(i)) then
sum:=sum+a[i];
br:=br+1;
average:=sum/br;
writeln('average= ',average:5:3);
readln;
end.
但是,当我开始我的程序时,它只找到总和,而计数器(br)不起作用,只计算总和。你能帮我解决这个问题,取决于我的代码吗:)!
答案 0 :(得分:0)
需要放置begin
和end
,以便br
正确递增:
if not(odd(a[i])) and (odd(i)) then
Begin
sum:=sum+a[i];
br:=br+1;
End;
average:=sum/br;
答案 1 :(得分:0)
使用内置例程[System.]Math.Mean:
program Project1;
{$APPTYPE CONSOLE}
uses
System.SysUtils, System.Types, System.Math;
var
Count: Integer;
I: Integer;
Values: TSingleDynArray;
begin
try
Write('Enter number of elements of the array: ');
ReadLn(Count);
SetLength(Values, Count);
for I := 0 to Count - 1 do
begin
Write('Enter element ', I + 1, ': ');
ReadLn(Values[I]);
end;
WriteLn('Average = ', Mean(Values):5:3);
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
答案 2 :(得分:-1)
试试这个:
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
TVector = array of integer;
var
a: TVector;
i, n: integer;
ElSum, Elements: integer;
begin
write('Enter number of elements: ');
readln(n);
SetLength(a, n);
for i := 1 to n do
begin
write('Enter ', i, ' element: ');
readln(a[i - 1]);
end;
ElSum := 0;
Elements := 0;
for i := 1 to n do
if not(odd(a[i - 1])) and (odd(i)) then
begin
inc(ElSum, a[i - 1]);
inc(Elements);
end;
if Elements <> 0 then
writeln('The average is: ' + floattostr(ElSum / Elements))
else
writeln('Can not divide by 0');
readln;
end.
<强>所附强>
在这种情况下,数据将在输入时进行分析。我假设你将来不需要数组的元素。这就是为什么我不将值存储在数组中。我也跳过FloatToStr
函数。
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
//We skip uses System.SysUtils;
var
i, n, CurrentInteger,
ElSum, Elements: integer;
begin
ElSum := 0;
Elements := 0;
write('Enter number of elements: ');
readln(n);
for i := 1 to n do
begin
write('Enter ', i, ' element: ');
readln(CurrentInteger);
if not(odd(CurrentInteger)) and (odd(i)) then
begin
inc(ElSum, CurrentInteger);
inc(Elements);
end;
end;
if Elements <> 0 then
begin
write('The average is: ');
writeln(ElSum / Elements:5:3)//we write it instead of FloatToStr
end
else
writeln('Can not divide by 0');
readln;
end.