【问题标题】:Having trouble looping through an array in c++ [closed]在c ++中循环遍历数组时遇到问题[关闭]
【发布时间】:2018-10-04 20:40:20
【问题描述】:

我似乎在循环我的数组时出错了,我已经将它设置为提示用户输入数字列表,并且我应该将它与用户设置的另一个数字进行比较。

#include <iostream>
using namespace std;
bool chk = true;
int main() {
    /*
    Write a program that asks the user to type 10 integers of an array and an integer s.
    Then search the value s from the array and display the value of s if it is found in
    the array otherwise print sorry not found..
    */

    int userArray[10], i, greater = 0;
    int s;
    cout << "Enter a check number: \n";
    cin >> s;
    if (chk = true) {
    //prompt for array list
        for (i = 0; i < 9; i++) {

            if (i == 0) {
                cout << "Enter ten numbers: " << "\n";
                cin >> userArray[i];
            }
            else {
                cin >> userArray[i];
            }
            chk = false;
        }
        //loop through the array
        for (int i = 0; i <= 10; i++) {
            if (s = userArray[i]) {
                //for testing
                cout << userArray[i];
                //cout << s;
            }
            else {
                cout << "No match found!";
            }
            //I was just using this to pause the console and let me inspect result
            cin >> greater;

        return 0;

        }
    }
}

我假设以下代码是问题所在。这个想法是我设置 s = 2 输入一个数字列表,然后与 s 进行比较,如果没有匹配则打印 s 我打印没有找到匹配项。当我输入一个我知道与 s 匹配的数字时,它似乎打印了数组中的第一个数字,但我认为因为我在 for 循环中一个一个地循环遍历数字,所以它应该在到达正确的数字时显示,而不是在它停止了。提前致谢

    //loop through the array
    for (int i = 0; i <= 10; i++) {
        if (s = userArray[i]) {
            //for testing
            cout << userArray[i];
            //cout << s;
        }
        else {
            cout << "No match found!";
        }

【问题讨论】:

  • 检查您的return 0; 的放置位置。 i &lt;= 10 也应该是 i &lt; 10
  • 尝试使用最高的编译器警告,然后编译器会指出错误。

标签: c++ arrays visual-c++


【解决方案1】:

您使用的是单个等号。这是将s 设置为userArray[i],因此它始终评估为真。对于比较,请使用双等号,如下所示:
if (s == userArray[i]) {...}
此外,您的 return 语句在您的循环中(归功于 @UnholySheep)。

【讨论】:

    【解决方案2】:

    您正在与单个赋值运算符 = 进行比较,您应该使用等于运算符而不是 ==

    if (s = userArray[i]) 在 for 循环中就是一个例子。

    你也犯了同样的错误

    if (chk = true)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      相关资源
      最近更新 更多