c++ - 检查同时向前和向后移动的数组并发出打印存储在指针数组中的值的问题
问题描述
前言:目前正在自学C++,所以请原谅我的一些无知。
我面临的挑战是编写一个程序来搜索具有函数的静态数组并返回您正在搜索的数字的索引。这只需要 1 个功能和最少的努力,所以我决定让它更“复杂”,以练习更多我迄今为止学到的东西。我大部分都成功了,但是我的 for 循环中的 if 语句存在问题。我希望他们检查传递给它的数组中的 2 个单独的点,但它正在检查它们的相同索引。我似乎也无法将索引作为输出。我可以获得正确数量的内存位置,但不是正确的值。我的代码有些混乱,我知道有更有效的方法可以做到这一点。我也很想被展示这些方式,但我也想了解我的错误在哪里以及如何解决它。另外,我知道 5 不会总是出现在数组中,因为我使用的是伪随机数生成器。先感谢您。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// This is supposed to walk throught the array both backwards and forwards checking for the value entered and
// incrementing the count so you know the size of the array you need to create in the next function.
int test(int A[], int size, int number) {
int count = 0;
for (int i = 0; i <= size; i++, size--)
{
if (A[i] == number)
count++;
// Does not walk backwards through the array. Why?
if (A[size] == number)
count++;
}
cout << "Count is: " << count << endl;
return (count);
}
// This is a linear search that creates a pointer array from the previous "count" variable in function test.
// It should store the indices of the value you are searching for in this newly created array.
int * search(int A[], int size, int number, int arr_size){
int *p = new int[arr_size];
int count =0;
for(int i = 0; i < size; i++){
if(A[i]==number) {
p[count] = i;
}
count++;
}
return p;
}
int main(){
// Initializing the array to zero just to be safe
int arr[99]={0},x;
srand(time(0));
// Populating the array with random numbers in between 1-100
for (int i = 0; i < 100; i++)
arr[i]= (rand()%100 + 1);
// Was using this to check if the variable was actually in the array.
// for(int x : arr)
// cout << x << " ";
// Selecting the number you wish to search for.
// cout << "Enter the number you wish to search for between 1 and 100: ";
// cin >> x;
// Just using 5 as a test case.
x = 5;
// This returns the number of instances it finds the number you're looking for
int count = test(arr, (sizeof(arr)/4), x);
// If your count returns 0 that means the number wasn't found so no need to continue.
if(count == 0){
cout << "Your number was not found " << endl;
return 0;
}
// This should return the address array created in the function "search"
int *index = search(arr, (sizeof(arr)/4), x, count);
// This should increment through the array which address you assigned to index.
for(int i=0; i < count; i++) {
// I can get the correct number of addresses based on count, just not the indices themselves.
cout << &index[i] << " " << endl;
}
return 0;
}
我非常感谢您的帮助和耐心,并再次感谢您的帮助。
解决方案
推荐阅读
- arrays - 在c中的数组中添加带有循环的元素的问题
- ios - React Native App 的 Facebook 登录实现失败
- php - 为什么我得到 403 Forbidden with Guzzle?
- python - 按键事件不适用于 tkinter 中的 FigureCanvas
- windows - 如何从版本号获取 Windows 操作系统名称
- java - 从底部导航中选择时,如何阻止片段重新加载 WebView?
- c# - 枚举数组包含字符串字典键 C#
- google-cloud-spanner - 不支持语句:CreateIndexStatement
- c# - 如何使用 C# 将 JSON 对象解析为类
- python - 如何运行 pb 文件?我有一个 pb 文件,我想运行图表,所有这些。以下是我尝试过的