You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将C语言素数判断代码中的while循环改为for循环并保持输出不变

修改后完整代码

#include<stdio.h>
int main(){
    int n, sum = 0;
    // 输入校验的do-while逻辑保留,和原代码完全一致
    do{
        printf("enter a positive number to find whether prime or not: ");
        scanf("%d",&n);
    } while (n <= 0);
    // 原有while循环替换为等价for循环
    for(int i = 1; i <= n; i++){
        if (n % i == 0) sum += 1; // sum为因数计数标记
    }
    if (sum > 2) 
        printf("\nThe number %d is not prime.", n);
    else
        printf("\nThe number %d is prime.", n);
    return 0;
}

改动说明

  • 核心逻辑完全复用原代码,仅将遍历除数的while循环替换为for循环格式:for循环括号内的三个参数刚好对应while循环的变量初始化、循环终止条件、每轮变量更新三个核心要素,运行逻辑和原代码100%一致,输出结果完全相同
  • 如果使用C99之前的旧标准不支持在for循环内部声明变量,只需要保留原代码开头的int i = 1定义,将for循环写为for(i = 1; i <= n; i++)即可正常运行

内容的提问来源于stack exchange,提问作者misfit101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 07:15:05