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

Count变量自增异常:JAVA出现次数统计结果与预期不符

问题原因与解决方案

问题根源在于你定义的变量名count和C++标准库中的std::count算法函数重名。由于你使用了using namespace std;,编译器会将count优先解析为标准库函数,而非你声明的整型变量,最终导致计数逻辑无法正确执行。

解决方案一:修改变量名

将变量名改为不会与标准库冲突的名称,比如java_count:

#include <bits/stdc++.h>
using namespace std;
int main(){
    string arr[8];
    
    for(int i=0;i<8;i++){
        cin>>arr[i];
    }
    int java_count=0;
    for(int i=0;i<8;i++){
        if(arr[i]== "JAVA"){
            java_count+=1;
        }
    }
    
    cout<<"JAVA lecture is repeating "<<java_count<<" times";
}

解决方案二:移除using namespace std;,使用标准库前缀

明确指定标准库命名空间,避免全局命名空间污染:

#include <bits/stdc++.h>
int main(){
    std::string arr[8];
    
    for(int i=0;i<8;i++){
        std::cin>>arr[i];
    }
    int count=0;
    for(int i=0;i<8;i++){
        if(arr[i]== "JAVA"){
            count+=1;
        }
    }
    
    std::cout<<"JAVA lecture is repeating "<<count<<" times";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:51:17