gpt4 book ai didi

c++ - 如何通过将数组的指针传递给函数来找到数组的模式? C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:10:36 26 4
gpt4 key购买 nike

所以我对指针完全陌生,对此我深表歉意,我应该传递一个指针数组并获取该数组的模式。数组作为一组指针传递后,我无法操作数组来查找模式,我尝试的所有操作都会导致语法错误。

编辑:我将列表更改为指针数组,但出现运行时错误。

int main()
{
int size=0;
int *list[size];
cout<<"Please enter the size of your array: ";
cin>>size;
cout<<"\nPlease enter the numbers in your list seperated by spaces: ";
for(int i=0;i<size;i++)
{
cin>>*list[i];
}
cout<<endl;


int mode=getMode(list,size);
cout<<"\n"<<mode<<endl;
return 0;
}

int getMode (int* list[], int arraySize)
{
cout<<"The array you entered is listed below\n "<<list[0];
for(int i=0;i<arraySize;i++)
{cout<<setw(3)<<list[i];}
int *number=list[0];
int count1=0;
int count2=0;
int mode=0;
for(int j=1;j<arraySize;j++)
{
for(int i=1;i<arraySize;i++)
{
if(list[i]==number)
{
count1++; //counts the number of instances that the number occurs
}
}
if(count1>count2)
{
mode= *list[j];
count2=count1;
}
count1=0;
}
return mode;
}

最佳答案

当你将一个数组传递给一个函数时,它会自动衰减为一个指针,所以你不需要使用&list。在函数中,你不应该声明它 int *list[],它应该只是 int list[]int *list .

另外,在getMode()函数中,需要统计list[j]的匹配项。您只是在计算 number 的重复次数,即 list[0]

#include <iostream>
#include <iomanip>
using namespace std;

int getMode (int list[], int arraySize)
{
cout<<"The array you entered is listed below\n "<<list[0];
for(int i=0;i<arraySize;i++)
{cout<<setw(3)<<list[i];}
int count1=0;
int count2=0;
int mode=0;
for(int j=0;j<arraySize;j++)
{
for(int i=0;i<arraySize;i++)
{
if(list[i]==list[j])
{
count1++; //counts the number of instances that the number occurs
}
}
if(count1>count2)
{
mode= list[j];
count2=count1;
}
count1=0;
}
return mode;
}

int main()
{
int size;
int *list;
cout<<"Please enter the size of your array: ";
cin>>size;
list=new int[size];
cout<<"\nPlease enter the numbers in your list seperated by spaces: ";
for(int i=0;i<size;i++)
{
cin>>list[i];
}
cout<<endl;

int mode=getMode(list,size);
cout<<"\n"<<mode<<endl;
return 0;
}

DEMO

关于c++ - 如何通过将数组的指针传递给函数来找到数组的模式? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42184238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com