首页 > 解决方案 > 循环崩溃

问题描述

如果我输入两位整数进行搜索,为什么循环会崩溃?它适用于单个数字整数。帮帮我。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    double arr[] = { 15, 29, 38, 47, 56, 64, 72, 83 };
    int size = sizeof(arr) / sizeof(arr[0]);
    for (int n = 0; n <= size; n++) {
        cout << "Enter the number to search:  ";
        cin >> n;
        for (int i = 0; i < size; i++) {
            if (arr[i] == n) {
                cout << "The number is in index no: " << i << endl
                     << endl;
            }
        }
    }
    return 0;
}

标签: c++

解决方案


您的程序可能没有崩溃,它只是比您预期的要早结束。当您同时使用n外部循环索引和输入值时,您的循环将在您输入 8 或更大的值后结束,n <= size并将返回false

您需要为输入数字使用单独的变量:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    double arr[] = { 15, 29, 38, 47, 56, 64, 72, 83 };
    int size = sizeof(arr) / sizeof(arr[0]);
    for (int j = 0; j <= size; j++) {
        cout << "Enter the number to search:  ";
        int n;
        cin >> n;
        for (int i = 0; i < size; i++) {
            if (arr[i] == n) {
                cout << "The number is in index no: " << i << "\n\n";
            }
        }
    }
    return 0;
}

推荐阅读