Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用if…else语句从随机生成的数字数组中提取特定数字?_C++ - Fatal编程技术网

C++ 如何使用if…else语句从随机生成的数字数组中提取特定数字?

C++ 如何使用if…else语句从随机生成的数字数组中提取特定数字?,c++,C++,来自随机生成的数字数组。您在此处使用if-else语句的原因是什么? 您可以使用for循环来迭代元素 examData.isNumberFound(100); for(int i=0;i

来自随机生成的数字数组。

您在此处使用if-else语句的原因是什么? 您可以使用for循环来迭代元素

examData.isNumberFound(100);
for(int i=0;icout如果我正确理解您的问题,您必须检查给定的数字是否在随机生成的数字列表中

我不知道你到底期望什么:

for(int i = 0; i < numOfElements; i++) {
    if(data[i] == someNumber) {
        cout << "Congrats, perfect score!" << endl;
        return true;
    }
}
// Nothing matched..
cout << "Sorry, you do not have a perfect score." << endl;
return false;
此语句只检查数组中的一个元素,即位于索引
SIZE
处的元素。另外还有一个问题:如果
SIZE
对应于数组的大小,则读取超出了数组的限制(=分段错误)。如果数组的大小为
N
,则有效索引将从
0
变为
N-1

如果这样说,您应该修改代码,添加一个检查数组所有元素的。使用,如下所示:

if (data[SIZE] == someNumber)
boolstatsarray::isNumberFound(int-someNumber){
对于(int i=0;i您要找的是cout?我不明白您的问题。是否要在数组
数据
中搜索
100
?访问
数据[SIZE]
很可能意味着分段错误。如果数组的大小为给定的
N
,则可以访问的元素索引从
0
N-1
if (data[SIZE] == someNumber)
bool StatsArray::isNumberFound(int someNumber) {

    for (int i = 0; i < SIZE; i++) {
        if (data[i] == someNumber) {
            cout << "Congrats, you have a perfect score!" << endl;
            return true; //You have found your number, exit the function
        }
    }

    ///You have checked the whole array and the value is not there
    cout << "Sorry, you do not have a perfect score." << endl;
    return false;

}