有人可以解释为什么该程序显示我 6 和 4

Can someone explain why the program shows me 6 and 4?

本文关键字:显示 程序 解释 为什么      更新时间:2023-10-16

在这个问题中,这是一个简单而简单的问题,我做总和和乘积。我想用一个"for"指令来理解这个东西是如何工作的。

#include < iostream >
using namespace std;
int main()
{
    int n,i,s=0,p=1;
    cin>>n;
    for (i=1;i<=n;i++)
         s=s+i;
         p=p*i;
        cout<<s<<" "<<p;
}

我无法解释为什么结果是总和"6"和乘积"4"......

有人可以解释我为什么代码显示这一点吗?如果我将"for"结构中的指令放在大括号之间,它显示"6"表示总和,"6"表示乘积。

首先,它不是< iostream >,而是<iostream>。那里不允许有空格。其次,尽管有缩进,p=p*i;还是在for环之外。打开编译器警告:

prog.cc:7:5: warning: this 'for' clause does not guard... [-Wmisleading-indentation]
    7 |     for (i=1;i<=n;i++)
      |     ^~~
prog.cc:9:10: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'for'
    9 |          p=p*i;
      |          ^

使用{}解决此问题:

for (i=1;i<=n;i++)
{
         s=s+i;
         p=p*i;
}