循环控制
#include <stdio.h>
int main()
{
int x;
scanf("%d", &x);
int i;
int isPrime = 1; //x是素数
for ( i=2; i<x; i++ )
{
if( x % i == 0 )
{
isPrime = 0;
break; //跳出任何循环
//continue 跳过循环这一轮要做的剩下的语句,进入下一轮循环
}
}
if (isPrime == 1)
{
printf("是素数\n");
} else
{
printf("不是素数\n");
}
return 0;
}
多重循环
找素数
#include <stdio.h>
int main()
{
int x = 0;
for ( x = 2; x<100; x++)
{
int i;
int isPrime = 1;
for ( i=2; i<x; i++ )
{
if ( x % 1 == 0)
{
isPrime = 0;
break;
}
}
if ( isPrime == 1 )
{
printf("%d", x);
}
}
printf("\n");
return 0;
}
//100内的素数
//以下是前50个素数:
#include <stdio.h>
int main()
{
int x = 2;
int cnt = 0;
while ( cnt<50 )
{
int i;
int isPrime = 1;
for ( i=2; i<x; i++ )
{
if ( x % 1 == 0)
{
isPrime = 0;
break;
}
}
if ( isPrime == 1 )
{
printf("%d", x);
cnt++;
}
x++;
}
printf("\n");
return 0;
}
凑硬币
//得出所有结果;
#include <stdio.h>
int main()
{
int x;
int one, two, five;
x = 2; //凑出两元钱
for ( one = 1; one < x*10; one++ )
{
for ( two = 1; two < x*10/2; two++ )
{
for( five = 1; five < x*10/5; five++ )
{
if ( one + two*2 +five*5 == x*10 )
{
printf("可以用%d个一角加%d个两角加%d远\n", oen, two, five, x);
}
}
}
}
return 0;
}
//break、continue只能离开最内层的一个循环
//以下是只有一个结果输出
#include <stdio.h>
int main()
{
int x;
int one, two, five;
x = 2; //凑出两元钱
for ( one = 1; one < x*10; one++ )
{
for ( two = 1; two < x*10/2; two++ )
{
for( five = 1; five < x*10/5; five++ )
{
if ( one + two*2 +five*5 == x*10 )
{
printf("可以用%d个一角加%d个两角加%d远\n", oen, two, five, x);
goto out; //程序直接跳到goto [标志] 中标志的地方,谨慎使用goto
}
}
}
}
out:
return 0;
}