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

如何在C语言数组查找程序中统计for循环的执行迭代次数

代码修改说明

  • 修正原代码语法问题:补全标准输入输出头文件引用,修正数组定义不规范、数组名前后不一致的问题,数组初始化值用大括号包裹
  • 新增循环执行次数统计逻辑:每次循环未匹配到目标值时打印当前迭代次数,匹配成功后直接输出位置信息,运行效果符合要求

完整可运行代码

#include <stdio.h>
int main(){    
    int data[] = {5,1,3,6,4,5,7,12,8,9,10};
    int i = 0, number;
    int NumberFound = 0;
    
    printf("Enter the number you are looking for: \n");
    // 非VS编译环境请将scanf_s替换为scanf
    scanf_s("%d", &number);
    for (i = 0; i < 11; i++) {
        if (number == data[i]) {
            NumberFound = 1;
            printf("%d was found in the position %d\n", number, i);
            break;
        }
        else {
            NumberFound = 0;
            printf("Iteration %d\n", i+1);
        }
    }
    
    if (NumberFound == 0) {
        printf("%d was not found \n", number);
    }
    
    return 0;
}

运行效果验证

输入数字3时,输出结果和你给出的示例完全一致:

Enter the number you are looking for:
3
Iteration 1
Iteration 2
3 was found in the position 2

如果需要中文输出,将对应printf内的文本替换为中文即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:45:07