【发布时间】:2020-12-10 04:17:31
【问题描述】:
我想将 n / anzahl 的输入和最低和最高温度的输出放在主函数中,同时在 void 函数中进行计算。我认为我的错误是调用了错误的参考,但我看不到它。有人可以帮我看看我的错误吗?
到目前为止,我得到了这个。这段代码是主函数中的所有内容,它运行良好,但我在实现将输出放入主函数时遇到了问题
#include <iostream>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
int n,i;
int groesst, kleinst;
int rand(void);
cout << "Geben Sie Anzahl der Temperaturwerte an: "; //put in the amount of temperatures
cin >> n;
n=n+1; //so non programmers arent confused
vector<int> temp(n);
cout << "31 zufaellige Temperaturen:\n" << endl;
groesst = temp[0];
kleinst = temp[0];
for (i=1;i<n;i++)
{
temp[i]=rand()%20-4;//random temperature between -4 and 15
cout << temp[i] << " Grad Celsius"<< endl;
if (temp[i]>groesst) //
{
groesst = temp[i]; //
}
if (temp[i]<kleinst)
{
kleinst = temp [i];
}
}
cout << kleinst; //minimum temperature
cout << "\n";
cout << groesst; //maximum temperature
return 0;
}
这是我的尝试:
#include <iostream>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <iomanip>
using namespace std;
void minmaxim(vector<int>& temp, int& n, int& kleinst, int& groesst)
{
int i;
int rand(void);
temp[n];
groesst = temp[0];
kleinst = temp[0];
for (i=1;i<n;i++)
{
temp[i]=rand()%20-4;
if (temp[i]>groesst)
groesst = temp[i];
}
if (temp[i]<kleinst)
{
kleinst = temp [i];
}
return;
}
int main ()
{
vector<int> temps;
int anzahl, minimum,maximum;
cout << "Geben Sie die Anzahl der Temperaturwerte ein: "; //type in the amounts of temperatures
cin >> anzahl;
minmaxim(temps, anzahl, minimum, maximum); //calling the function
cout << " " << anzahl;
cout << " " << minimum <<endl;
cout << " " << maximum <<endl;
return 0;
}
【问题讨论】:
-
您能解释一下您遇到的问题吗?它没有编译,是打印错误的值,还是?
-
哦 - 首先你要调整矢量的大小,例如
temps.resize(n);。实际上,我认为您只是在使用未定义的内存。 -
除了我应该输入的内容外,它没有打印任何内容,所以`“Geben Sie die Anzahl der Temperaturwerte ein:” `
标签: c++ function input output pass-by-reference