【问题标题】:how to compare unknown elements of an array in c++?如何在 C++ 中比较数组的未知元素?
【发布时间】:2023-01-25 23:53:39
【问题描述】:

抱歉英语不好。 我试图编写一个程序来获取数字并查看输入数字的数字是否重复。我确实尝试过 if(analyse[0]==analyse[1]==analyse[2]==...) 但是因为我不知道数组会有多少元素,所以它没有用

#include<iostream>
int main(){
    int number,number_help;
    const int count{10};
    std::cin>>number;
    number_help = number ;
    int digitcount{0};
    while(number_help>0){
        number_help/=10;
        digitcount+=1;
    }
    int analyse[count]{};
    for(size_t i {0}; i<digitcount ; i++){
        analyse[i] = number%10;
        number/=10;
    }
    //I don't know what to code here
    return 0;
}

【问题讨论】:

  • analyse 总是有 10 个元素。无论如何,a == b == c 并没有按照您的想法去做。 The Definitive C++ Book Guide and List 应该有帮助。
  • int analyse[count]{}; - 无论哪本 C++ 教科书告诉你这样做 - 你需要立即扔掉它,并获得不同的 C++ 教科书。如果您从某个网站复制了它,请不要再访问该网站。如果您在某个小丑的 Youtube 视频中看到这个,请取消订阅该频道,您就没有学习正确的 C++。这不是标准的 C++,许多 C++ 编译器会拒绝编译它。
  • 如果count是一个用文字初始化的整数常量(这里是10),那么代码是可以的——countcan be used as a constant expression
  • @SamVarshavchik int analyse[count]{}; 怎么了? count 是常量表达式。
  • 有点跑题了,但是如果你使用std::vector<int>而不是“C”风格的数组来进行分析,你就不必预先计算它的大小,你可以 push_back 更多的数字。 std::vector 是当您事先不知道数组大小时要使用的类型。

标签: c++ arrays


【解决方案1】:

改变你的方法:计算每个数字有多少,而不是将它们相互比较。
这要简单得多。

例子:

#include<iostream>

int main(){
    int number;
    std::cin >> number;
    const int count{10};
    int frequency[count]{};
    do {
        frequency[number % 10] += 1;
        number /= 10;
    } while (number != 0);
    for (int i{0}; i < count; i++) {
        if (frequency[i] > 1) {
            std::cout << i << " was repeated " << frequency[i] << " times.
";
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2011-08-05
    • 1970-01-01
    • 2016-03-25
    相关资源
    最近更新 更多