关于循环中r的问题,为什么还是循环了
#include <iostream>
#include <cmath>
using namespace std;
void Getsushu(int start=1,int end=200)
{
for(int i=start;i<=end;i++)
{
int r,nsqrt;
nsqrt=sqrt(i);
for(r=2;r<=nsqrt;r++)
{
if(i%r==0) break;
}
if(r>nsqrt) cout<<i<<" ";
}
cout<<endl;
}
void main()
{
int st,ed;
cout<<"输入查找范围的首尾:"<<endl;
cin>>st>>ed;
cout<<st<<"到"<<ed<<"之间的素数如下:"<<endl;
Getsushu(st,ed);
}
这段代码我刚刚写的,相信大家都知道它的作用。可是之间有一些问题我不解。望大家指教:
for(r=2;r<=nsqrt;r++)
{
if(i%r==0) break;
}
if(r>nsqrt) cout<<i<<" ";//在这个地方的r不在for的循环作用域之内吧,可是下面运行时却没有问题,一个不落的把所有素数都输出了,我觉得是有问题的,可是运行没问题,迷惑,短路了。谁能给我解释一下为什么呢?感激的!
[解决办法]
for(r=2;r<=nsqrt;r++)
{
if(i%r==0) break;
}
看这个小循环 里面先给r赋值了
当if(i%r==0) break;条件触发的时候 r已经被赋值了
比如
int n = 0;
for(n = 0; n<10; n++)
{
if (n == 5) break;
}
运行到这里 n 已经等于5了