如何在 cpp 的 main() 中调用此函数

How to call this function in main() in cpp

本文关键字:调用 函数 main cpp      更新时间:2023-10-16

我正在尝试在main((函数中使用以下remove((函数。请让我知道我当前的代码有什么问题。

void remove(float a[], int& n, int i);
int main() {
float a[]={56.8, 14.2, 0.2, 22.3, 3.3, 54.02, 543.33, 456,333, 1.1};
int size, del;
size =sizeof(a)/sizeof(a[0]);
cout<<"Enter the element to be deleted!";
cin >>del;
cout << "Removed= "<< remove(a, size, del) << "n";
}
void remove(float a[], int& n, int i){
for (int j=i+1; j<n; j++)
a[j-1] = a[j];
--n;
}

所以你的问题是

a( 让我知道我的代码出了什么问题

b( 有没有另一种方法可以在不更改函数代码的情况下做同样的事情

至 a(

  1. 我最近了解到如果可能的话不要使用命名空间,因为由于实际上经常发生的变量命名,很有可能出现可避免的错误 - 所以建议使用std::而不是using namespace std;

  2. sizeof()可能会使用内部双精度不浮动,所以在它旁边工作我的警告:implicit conversion loses floating-point precision: 'double' to 'float'

  3. 正文中具有多行的 for - 斜率应写在括号中,否则我的警告:此"for"子句不保护...[-误导缩进] 20 | for (int j=i+1; j

  4. 如果您使用std::cin则始终应该检查错误的输入,例如,就像我对input()函数所做的那样。

  5. 由于int main(){return 0;}是一个函数,并且"int"表示返回值,因此请始终使用"return 0"关闭函数,以向操作系统发出停止信号。

  6. 开头而不是行间声明变量使代码更具可读性

  7. 另外,如果您得到正确的答案,请不要忘记检查您的问题是否已解决,以避免它出现在 stackoverflow.com ;)的"未解决"部分中

至 b(

是的,它是 - 除了使用 { } - 括号如下:

#include <iostream> //std, std::cin
#include <limits> //std::numeric_limits<std::streamsize>::max()
int input(int size); //int signals return
void remove(double a[], int& n, int i); //void signals no return
int main() {
int size, del;
double rem;
double a[]={56.8, 14.2, 0.2, 22.3, 3.3, 54.02, 543.33, 456,333, 1.1};
size =sizeof(a)/sizeof(a[0]);
std::cout<<"Which element do you want to remove: ";
del = input(size); //check the input
rem = a[del]; //filling rem to print out the value to be removed to not change the function like you asked for
std::cout << "Removed= " << rem << std::endl; 
remove(a, size, del); 
return 0;
}
void remove(double a[], int& n, int i)
{
for (int j=i+1; j<n; j++)
{
a[j-1] = a[j];
--n;
}
}
int input(int size)
{
int input;
while (!(std::cin >> input) || input < 0 || input >= size) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cout << "invalid input ignored; try again and enter a valid move between -1 and " << size << "n";
}
return input;
}

我的目的是让包括我自己在内的每个人都能从看似简单的问题中学习。我希望我达到了我的目标:)

float remove(float a[], int& n, int i);
int main() {
float a[]={56.8, 14.2, 0.2, 22.3, 3.3, 54.02, 543.33, 456,333, 1.1};
int size, del;
size =sizeof(a)/sizeof(a[0]);
cout<<"Which element do you want to remove: ";
cin >>del;
remove (a, size, del);
}
float remove(float a[], int& n, int i){
cout << "Removed= "<< a[i] << "n";
for (int j=i+1; j<n; j++)
a[j-1] = a[j];
--n;
return i;
}
float remove(float a[], int& n, int i){
float deleted = a[i]; 
for (int j=i+1; j<n; j++)
a[j-1] = a[j];
--n;
return deleted;
}

在 remove 函数中添加 return 语句并相应地更改返回类型。