我在C ++课程中遇到编码分配问题。赋值要求我们有可变长度数组调用函数。每当我尝试将函数调用到main时,我就会在标题中出现错误。我已经看到了类似的其他问题,但我似乎无法解决任何解决它们的问题。
`# include <iostream> //Allows user input
using namespace std;
int i, hold; //Global variables for use in functions and loops through-out the program.
//Functions below main.
int main()
{
int length=0;
int* a = new int[length];; //This array has 'length' spaces.
cout << "How many numbers would you like to sort?\n";
cin >> length;
for(i=0;i<length;i++) //This loop populates the array.
{
cout << "Enter a number.\n";
cin >> a[i];
}
cout << "This doesn't work ->" << sortDescending(a, length) << endl;
cout << "This also doesn't work" << shiftRight(a, length) << endl;
return 0;
}
以下是功能本身。
void sortDescending(int a[], int length) //Sorts the numbers in the array in descending order.
{
for(i=0;i<length;i++)
{
if(a[i]<a[i+1]) //Detects if the first number is smaller than the second.
{ //If the first is smaller than the second then this swaps them.
hold=a[i];
a[i]=a[i+1];
a[i+1]=hold;
}
}
}
void shiftRight(int a[], int length)
{
for(i=0;i<length;i++)
{
a[length-i]=a[length-(i-1)];
}
}
答案 0 :(得分:1)
两个函数sortDescending()
和shiftRight()
都是void
返回函数。返回void
的函数没有返回语句,因此无法从调用中获取任何值。因此,试图&#34;打印&#34;以下代码中函数的返回值总是会失败:
... << sortDescending(a, length) << ...
... << shiftRight(a, length) << ...
我要采取措施,并假设您正在尝试打印实际的阵列。在调用函数后,可以使用for循环简单地完成此操作:
sortDescending(a, length);
std::cout << "After sortDescending(): ";
for (int i = 0; i < length; ++i)
{
std::cout << a[i] << " ";
}
std::cout << std::endl;
shiftRight(a, length);
std::cout << "After shiftRight(): ";
// Do the same as the above
为了更方便,您甚至可以在两个功能中打印阵列。但这是我要完成的任务。 :)
答案 1 :(得分:0)
不要使用排序功能。使用算法库
#include <algorithm>
然后按照这样排序:
cout << "This will work" << sort(a, a+length) << endl;