为什么这两份代码输出不一样?求大佬指点!

P1035 [NOIP2002 普及组] 级数求和

AMIRIOX無暝 @ 2020-02-19 17:11:44

为什么这两个代码输出不一样?(一个在if前面输出空格,一个没有,其他地方一样) 求大佬指点!谢谢!

using namespace std;
double S_n(int r){
    double Sr;
    for(int i=1; i<=r; i++){
        Sr += 1.0/i;
    }
    return Sr;
}

int main(){
    int k;
    cin >> k;
    for(int n = 1;;n++){
        double Sn = S_n(n);
        cout <<" ";//有这句,输入3输出就是11(正确)
        if(Sn > (double)k){
            cout << n;
            break;
        }
    }
    return 0;
}
#include <iostream>
using namespace std;
double S_n(int r){
    double Sr;
    for(int i=1; i<=r; i++){
        Sr += 1.0/i;
    }
    return Sr;
}

int main(){
    int k;
    cin >> k;
    for(int n = 1;;n++){
        double Sn = S_n(n);
        //cout <<" "; 这句注释掉输入3输出3
        if(Sn > (double)k){
            cout << n;
            break;
        }
    }
    return 0;
}

by Nerovix @ 2020-02-19 17:20:32

因为宁函数里面的Sr没有初始化


by Nerovix @ 2020-02-19 17:21:30

话说宁这么做是过不了这道题的会T


by AMIRIOX無暝 @ 2020-02-19 17:24:57

@wangdy 哦哦谢谢大佬了


by Nerovix @ 2020-02-19 17:25:53

我是菜鸡啦,刚开始做新手村的


by jijidawang @ 2020-02-19 17:29:55

@wangdy %%%


by Nerovix @ 2020-02-19 17:31:51

@jijidawang ?橙名膜绿名?orz


by jijidawang @ 2020-02-19 17:33:57

@wangdy 刚刷提高历练地的蒟蒻瑟瑟发抖,您太强了,我自愧不如啊


by Nerovix @ 2020-02-19 17:37:46

@jijidawang ?提高膜入门?orz


|