我正在开发从数组中删除重复项的程序,我在这里使用三个函数:一个函数用于获取输入,例如大小和数字,第二个函数用于删除重复项并返回没有重复项的数字,第三个函数只是一个报告显示尺寸和新数字,但我遇到问题,我不知道我在报告或 phillip erreur 中想到的步骤:
在函数
中:从‘int main()’
到‘int*’
的无效转换,初始化‘int’
的参数1‘void report(int, int)’
#include <iostream>
using namespace std;
const int size = 100;
void phillip(int[], int & );
/* Preconditions: Array of base type in declared and int varuable declared
postconditions: the array is filled with values supllied by the user at
the keybord. the user is assked how many values they want - this value is
given to the second argument.
*/
int remdubs(int[], int noel);
/* Preconditions: An array of basetype int that has noel values.
postconditions: The number of unique elemts in the array is returned. The function removes all dubplicates inside the array.
*/
void report(int s, int d);
int main()
{
int ruby[size];
int numele, numuniq;
phillip(ruby, numele);
numuniq = remdubs(ruby, numele);
report(ruby, numuniq);
return 0;
}
void phillip(int[], int& )
{
int s;
cout << "\nHow many values you want? ";
cin >> s;
cout << "\nPlease input 10 integers, hitting return after each one \n";
for (int i = 0; i < s; i++)
{
int num;
cin >> num;
}
}
int rembups(int sapphire[], int noel)
{
for (int i = 0; i < noel; i++)
{
for (int j = i + 1; j < noel; j++)
{
if (sapphire[i] == sapphire[j])
{
for (int k = j; k < noel; k++)
sapphire[k] = sapphire[k + 1];
noel--;
j--;
}
}
}
return noel;
}
void report(int s, int d)
{
cout << "\nYou entered " << s << "distinct numbers: " << d;
}
无法比你的错误更好地解释它:
void report (int s, int d);
此函数要求两个整数值,您将一个数组传递给它,该数组的功能已退化,其行为将类似于整数指针
int ruby[size];
report (ruby, numuniq);
我不确定你的程序的行为,但你应该这样做
report(ruby[0], numuniq);
即:访问数组的元素并将其提供给函数
错误出现在函数报告中,它要求两个整数,而您传递的是一个数组和一个整数 再说一次,我认为你不需要函数报告中的 2 个参数,一个就能解决你的目的
void report(int d)
{
cout << "\nYou entered <<d<<" distinct numbers";
}
这可以解决你的错误,但我认为你不会得到你想要的输出
您遇到的错误是由于
report
函数调用中的类型不匹配造成的。 report
函数被定义为以两个整数作为参数:
void report(int s, int d);
但是,在
main
函数中,您尝试传递一个数组 (ruby
) 作为第一个参数:
report(ruby, numuniq);
这就是错误消息“从
int*
到int
的无效转换”的原因,因为该函数需要一个int
,但您提供了一个int*
(指向int的指针,这就是数组衰减的内容)当传递给函数时)。
要解决此问题,您需要调整
report
函数以将数组及其大小作为参数,然后修改实现以正确输出数组的元素。方法如下:
首先,更改
report
函数的签名以接受数组及其大小:
void report(int arr[], int size);
然后,修改
report
函数以迭代数组并打印元素:
void report(int arr[], int size) {
cout << "\nYou entered " << size << " distinct numbers: ";
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
接下来,您的代码中还有一些问题需要解决:
phillip
函数中,您实际上并没有用用户的输入填充数组。您需要将输入存储在数组中:void phillip(int arr[], int& size) {
cout << "\nHow many values you want? ";
cin >> size;
cout << "\nPlease input " << size << " integers, hitting return after each one \n";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
}
remdubs
函数名称时存在拼写错误。它应该与声明相符:int remdubs(int sapphire[], int noel) {
// ... function implementation ...
}
您没有使用
size
常量。如果你想限制用户输入最多100个,你应该在phillip
函数中使用它,以防止用户输入超过100个元素。
现在应该使用正确的参数调用
report
中的 main
函数:
report(ruby, numuniq);
进行这些更改后,假设您的
remdubs
函数已正确实现以删除重复项,您的代码应该可以正常工作。