for爆炸求助

P1035 [NOIP2002 普及组] 级数求和

kemkra @ 2020-07-29 18:10:01

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int k, n;
    double s = 0;
    cin >> k;
    for (int n = 1; s <= k; n++) s += 1.0 / n;
    cout << n;
    return 0;
}

for出来后n炸了(s依然正常),不知所措?


by andyli @ 2020-07-29 18:12:23

for (int n = 1; s <= k; n++) s += 1.0 / n;

-->

for (n = 1; s <= k; n++) s += 1.0 / n;

by CarroT1212 @ 2020-07-29 18:13:03

在循环外部定义的变量不能在循环内在定义


by int64 @ 2020-07-29 18:27:51

@龚特_201912_Pg @龚特_201912_Pg 正解


by andyli @ 2020-07-29 18:34:27

@龚特_201912_Pg 不是不能定义


by kemkra @ 2020-07-29 18:35:10

okok,感谢大佬!!!


by Andy_chen @ 2020-07-29 18:56:37

@钻剑君 其实是可以的


by 青鸟_Blue_Bird @ 2020-07-29 18:58:36

@Andy_chen 可以定义,但是会出错啊。。


by 青鸟_Blue_Bird @ 2020-07-29 18:59:14

当然特殊情况可以


by Andy_chen @ 2020-07-29 19:02:42

@青鸟_Blue_Bird 不会CE,会WA


by wangzhengda @ 2020-08-13 18:00:39

n的作用域只在for里面。


|