C++基础之寻找给定范围内素数并输出

来源:互联网 发布:跨河水准测量数据整理 编辑:程序博客网 时间:2024/06/05 15:12
#include <iostream>#include <stdio.h>#include <stdlib.h>int main() {    int c=0;    printf("Input the lower bound\n");    int lb;    std::cin >> lb;    printf("Input the higher bound\n");    int hb;    std::cin >> hb;    int i,j;    int counter=0;    for(i=lb+1;i<hb;i=i+1){        for(j=2;j<i;j=j+1){           if(i%j==0)               counter++;}        if (counter==0){            std::cout<<i;            printf(" ");}        counter=0;    }    return 0;}

之所以po出这段代码来,是因为在笔者当初学C++时,这段代码改了很多遍,有笔者易犯的错误。

易错点在 counter=0 上,每遍历一遍i,在讨论下一个i时,要把counter重新设为0。这是初学者很容易犯的错误。


原创粉丝点击