简体   繁体   English

C ++程序永远循环

[英]C++ Program loops forever

I seem to be having an issue that I've been stuck on for hours. 我似乎遇到了一个问题,我已经坚持了几个小时。 I run the program, and it just hangs after asking for the user input. 我运行该程序,并在要求用户输入后挂起。 My computer also begins to slow down unless I terminate the program. 除非我终止程序,否则我的计算机也开始减速。 I have no idea what the problem is. 我不知道是什么问题。 I have tried commenting out code to see where the issue may be coming from. 我尝试注释掉代码,以查看问题可能来自何处。 I put a cout statement after asking for the input, and even that does not display. 在要求输入后,我放了一个cout语句,甚至不显示。

#include <iostream>
#include <vector>
#include <stdexcept>
#include <iomanip>
#include <cstdlib>
#include <array>
#include "problem2.h"

using namespace std;

int binarySearch(int array[], int input);
void selectSort(int arr[], int n);

int problem2() {
    srand(time(0));         // generate seed based on current system time

    int rand[20];
    int result;
    int input = 1;


    cout << "Enter a number to search for: ";
    cin >> input;

    cout << "testset ";

    for (int z = 0; z < 19; z++) {
        rand[z] = random() % 70;
        cout << rand[15];
    }


    selectSort(rand, 20);


    for (int t = 0; t < 20; t++) {
        //cout << random1D[z];
        }
    result = binarySearch(rand, input);
    //cout << result;

    return 0;
    }

int binarySearch(int arr[], int a) {
    int high = 19;
    int middle =  19/2;
    int low = 0;

    while (arr[middle] != a && low<= high) {
        if (arr[middle] > a) {
            high = middle - 1;
        } else {
            low = middle - 1;
        }

        if (low > high) {

        }
    }
    return middle;
}

void selectSort(int arr[], int n) {
    int min, temp;

    for (int i = 0; i < n-1; i++) {
        min = i;

        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[min])
                   min = j;
        }
        if (min != i) {
            temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
    }
}

You have several loops, but all of them except for one have explicit termination. 您有几个循环,但是除了一个循环外,所有循环都有显式终止。 The for loops all end after a specific number of iterations, but your while loop is less certain. for循环均在特定的迭代次数后结束,但是while循环不确定。 Your low is likely never going to be greater than your high , so the loop just keeps going. 您的low可能永远不会大于您的high ,因此循环一直持续下去。

Consider changing to low = middle + 1 or altering your logic to more likely ensure that low will eventually overtake high . 考虑更改为low = middle + 1或更改逻辑以更可能确保low最终超过high Or, change the condition the while loop checks. 或者,更改条件while循环检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM