请分别写出用for 和while 循环语句计算的程序。此外,还请写出避免循环的数值计算程序、符号计算程序。
提示:避免循环的数值计算使用sum指令。
该任务的目的:掌握for和while循环语句。
Matlab代码为:
% for loop
result = 0;
for i = 1:1000
result = result + 0.2^(i-1);
end
disp(result)
% while loop
result = 0;
i = 1;
while i < 1000
result = result + 0.2^(i-1);
i = i + 1;
end
disp(result)
结果为:
1.2500