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 <= 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;
}
解决方案
您的程序可能没有崩溃,它只是比您预期的要早结束。当您同时使用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;
}
推荐阅读
- google-cloud-platform - 如何在 BigQuery UI 中安排查询时修复“请求包含无效参数”错误
- c - 带有命名参数的函数指针?
- android - 如何使用具有日历时间的作业调度程序在特定时间运行作业
- r - R中的if语句:尽管存在值,但出现“缺失值”错误
- python - 通过 python 套接字发送字节序列
- python - 从 Pandas 数据框中删除值仅出现一次的行
- javascript - 使用 ParentElement 代替 ParentNode 的实际应用是什么?
- odoo - 批量编辑“stock_route_product”
- amazon-web-services - PermissionError:[Errno 13] 权限被拒绝:尽管在 AWS EC2 实例上正确运行,但无法在浏览器上打开 Jupyter
- java - 回到第一个视图/根视图的内容