C++ 环路崩溃

C++ 环路崩溃,c++,C++,如果输入两位数整数进行搜索,为什么循环会崩溃?它适用于单位数整数。帮帮我 #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 <=

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

#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;
}
#包括
#包括
使用名称空间std;
int main()
{
双arr[]={15,29,38,47,56,64,72,83};
int size=sizeof(arr)/sizeof(arr[0]);
对于(int n=0;n;
对于(int i=0;icout您的程序可能没有崩溃,它只是比您预期的更早结束。当您对外部循环索引和输入值使用
n
时,您的循环将在输入8或更多值后结束,因为
n提示一个问题:
for(int n=0;…){cin>>n..
我建议您在调试时很容易发现这些问题。我不认为这会导致崩溃。@molbdnio您的权利,所示的代码不应该崩溃。它可能不符合OP的预期,但不应该崩溃。我想您的问题是(int n=0;关于
endl
的注释
endl
是一个换行符,是对底层媒体的强制刷新。由于向媒体写入可能非常昂贵,因此通常只希望在强制执行时执行,例如当缓冲空间用完或必须立即显示消息时。您通常只希望换行符,因此更喜欢将
'\n'
写入流。但是,当我只输入单整数时,为什么循环会工作?:/@AR Hashmi尝试输入
9
作为数字,它是一个单位数,但会有相同的问题,因为数组中有8个元素。同样,请在调试器中逐步检查代码,它应该会使其恢复当你这样做的时候,你会清除所有的变量,同时监视所有的变量和它们的值。现在代码运行良好。我明白我的错误。那太愚蠢了。谢谢艾伦。)
#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;
}