除了一个小问题外,这段代码对我来说工作得很好。在调用我的 find_min
和 find_max
函数后,代码还打印出一个看似随机的数字。我认为这与按引用传递有关,它是一个内存值或其他东西。有人可以解释并告诉我如何摆脱它吗?谢谢。
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;
//get_avg function will get the average of all temperatures in the array by using for loop to add the numbers
double get_avg(int* arr, int n) {
double res = 0.0;
for(int i = 0; i<n; i++){
res += arr[i];
}
return (res/n); //average
}
void get_array(int* arr){
int i;
for(i=0; i<25; i++){
arr[i] = (rand() % 100) + 1;
}
}
//prints the results of get_avg in and get_array in table format, then finds difference between avg and temp.
void print_output(int* arr) {
double avg = get_avg(arr, 24);
cout << "The average is: " << avg << endl;
cout << "Position\tValue\t\tDifference from average\n\n";
char sign;
for(int i = 0; i < 24; i++){
sign = (avg > arr[i])?('+'):('-');
cout << i << "\t\t" << arr[i] << "\t\t" << sign << fabs(avg-arr[i]) << endl;
}
}
//finds the minimum function using a for loop
int find_min(int* arr, int n) {
int low = arr[0];
int index = 0;
for(int i = 1; i<n; i++){
if(arr[i] < low){
low = arr[i];
index = i;
}
}
cout << "The position of the minimum number in the array is "<< index <<" and the value is " << low << endl;
}
//finds the maximum function using a for loop
int find_max(int* arr, int n){
int hi = arr[0];
int index;
for(int i = 1; i<n; i++) {
if(arr[i] > hi) {
hi = arr[i];
index = i;
}
}
cout << "The position of the maximum number in the array is "<< index <<" and the value is " << hi << endl;
}
int main(){
int arr[24]; //declares array
get_array(arr);
print_output(arr);
cout << find_min(arr, 24) << endl;
cout << find_max(arr, 24) << endl;
cout << endl;
// wrap-up
cout << "This program is coded by Troy Wilms" << endl; // fill in your name
// stops the program to view the output until you type any character
return 0;
}
最佳答案
在这两行中:
cout << find_min(arr, 24) << endl;
cout << find_max(arr, 24) << endl;
你正在使用 std::cout
来打印这些函数的返回值(int),但是在你的函数定义中你没有返回任何值,所以它会打印一个垃圾值.
在函数的末尾(find_min
和 find_max
)添加 return arr[index];
关于C++函数在endl(内存变量?)之后打印不需要的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47119875/