while语句
案例一:s = 1 + 1/2 + 1/3 + 1/4 + 1/5 + ... + 1/19
# include <stdio.h>
/*
while 循环
*/
int main(){
// s = 1 + 1/2 + 1/3 + 1/4 + 1/5 + ... + 1/19
double s = 0;
int i = 1;
while(i <= 19){
printf("%d \n", i);
s += 1.0/i;
i++;
}
printf("s=%f \n",s);
return 0;
}
结果如下:
案例二:s = 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 ... + 1/19
# include <stdio.h>
/*
while 循环
*/
int main(){
// s = 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 ... + 1/19
double s = 0;
int i = 1;
while(i <= 19){
printf("%d \n", i);
if(i%2 == 0){ // i是偶数
s -= 1.0/i;
} else{
s += 1.0/i;
}
i++;
}
printf("s=%f \n",s);
return 0;
}
结果如下:
案例三:素数
判断素数:只有1和本身是它的因素。
# include <stdio.h>
/*
while 循环
*/
int main(){
int n ;
printf("请输入一个整数:");
scanf("%d", &n);
// printf("%f", sqrt(n-1));
int m = sqrt(n); // 平方根 100 →10
// 假设n是素数
int isPrime = 1;
// 开始循环判断
int i = 2;
while( i <= sqrt(m) ){
if (n%i == 0){
printf("%d能整除\n", i);
isPrime = 0;
// 跳出循环
break;
}
i++;
}
if(isPrime == 1){
printf("%d是素数",n);
} else{
printf("%d不是素数",n);
}
return 0;
}
结果如下: