跳转至

第五周 循环控制

一、for循环

  1. 阶乘
#include <stdio.h>
int main()
{
    int n, result = 1;
    int i = 1;      //设定i与result的初始值为1,否则相乘等于0
    scanf("%d",&n);
    for (;i<=n;i++){
        result = result * i;
    }
    printf("%d的阶乘为%d", n, result);
    return 0;
}

二、循环控制

  • break: 跳出循环
  • continue:跳过循环这一轮剩下的语句进入下一轮

  • 素数

#include <stdio.h>
int main()
{
    int x, rest, time = 0;
    scanf("%d",&x);
    int i = 2;
    for (;i<x;i++){
        rest = x % i;
        if (rest != 0)
            time ++;
        if (rest == 0){
            printf("是和数"); 
            break;
        }
    } 
    if (time == x - 2)
    printf("是素数");
    return 0;
}

标答

#include <stdio.h>
int main()
{
    int x;
    scanf("%d",&x);
    int i;
    int isprime = 1;
    for(i = 2; i < x ; i++){
        if (x % i==0){
            isprime = 0;
            break;
        }    
    }
    if (isprime == 0){
        printf("和数");
    }
    else {
        printf("素数")
    }
    return 0;
}

三、嵌套的循环

#include <stdio.h>
int main(){
    int a = 100, i = 1, b = 2;
    int c = 1;
    for(i = 1;i <= a;i++){
        for(b = 2, c = 1;b < i;b++){
            if (i % b == 0){
                c = 0;
                break;
            }
        }
        if (c == 1){
            printf("%d\t",i);   
        }
    }
    return 0;
}