You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算数组中奇数的乘积?Pascal代码运行问题修复求助

Pascal数组奇数乘积计算代码修复

错误点说明

  • 核心逻辑错误:奇数判断的if语句放在了数组读取的for循环外面,仅会执行一次。此时循环变量i的值为n+1,超出了已输入的数组元素下标范围,读取的是未初始化的无效值,因此计算结果错误。
  • 冗余内容:声明的c数组没有被使用,输出文本存在拼写错误produs应为product。

修复后代码

Program p2;
type 
    tab = array[1..10] of integer;
var 
    a : tab;
    n, i, prod : integer;
begin
    writeln('n=');
    readln(n);
    prod := 1;
    writeln('Enter array numbers:');

    for i := 1 to n do
    begin
        read(a[i]);
        if (a[i] mod 2 = 1) then
            prod := a[i] * prod;
    end;

    writeln('The product of the odd numbers is: ',prod);
end.

验证说明

针对测试场景输入n=5,数组元素依次为1、2、3、4、5时,修复后代码会遍历判断每一个数组元素,最终计算得到奇数乘积为1*3*5=15,符合预期结果。

内容的提问来源于stack exchange,提问作者Valentin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 14:18:04