请大佬帮看,while和for的区别

P1035 [NOIP2002 普及组] 级数求和

MrKeanu @ 2020-02-17 11:40:19

第一次是用for语句写的循环体,结果怎么都不对,但是用while语句写就对了,这是什么原因呢?

在测试中发现for语句最后n的值会多出1,这个与它的语句体有关吗?

楼下附上源代码。

for语句:

#include<stdio.h>

int main(){
    int n,k;
    double s=0.0;

    scanf("%d",&k);
    for(n=1;s<=k;n++){
        s =s+ 1.0/n;    
    printf("%d",n);

    return 0;
} 

while语句:

#include<stdio.h>

int main(){
    int n,k;
    double s=0.0;

    scanf("%d",&k);
    while(s<=k){
        n++;
        s+=1.0/n;
    }
    printf("%d",n);

    return 0;
} 

by iTwinkle @ 2020-02-17 11:41:53

好迷的for循环语句


by bunH2O @ 2020-02-17 11:42:25

for先加再判断,while直接判断


by iTwinkle @ 2020-02-17 11:42:27

你的n赋初值了吗


by UnyieldingTrilobite @ 2020-02-17 11:42:57

for先更新s再n++ while先n++再更新s


by UnyieldingTrilobite @ 2020-02-17 11:43:17

还有n没初始化


by cmll02 @ 2020-02-17 11:43:38

s<=k 时, n=n+1,再执行一次,此时 s>k,但仍然会再执行 n++,然后判断,跳出。


by iTwinkle @ 2020-02-17 11:43:54

for和while的执行顺序不一样,for是先执行再n+1,while语句里是n+1再执行


by pocafup @ 2020-02-17 11:44:04

for要定义次数


by iTwinkle @ 2020-02-17 11:44:55

@pocafup 不一定要规定次数,只要有终止条件就行了


by UnyieldingTrilobite @ 2020-02-17 11:45:01

while和for干嘛这么写不香吗

While the value of s is less than the value of k or the value of s equals the value of k do{
    Let the value of n be the value of n plus 1;
    Let the value of s be the value of s plus 1.0 divided by n;
}

| 下一页