【发布时间】:2018-04-17 14:36:10
【问题描述】:
除了一个小问题外,这段代码对我来说非常有效。调用我的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;
}
【问题讨论】:
-
您的
find_min和find_max被声明为返回int,但不返回任何内容。还可以考虑使用std::array(或std::vector)及其.size(),而不是幻数。 -
在
get_array函数中,您使用for(i=0; i<25; i++){,而其他所有内容都使用24作为数组大小。 -
使用
endl有时会出现问题。在任何情况下使用\n是更好的选择。 -
@AliSepehri-Amin,在任何情况中绝对不会更好。
endl刷新缓冲区,有时您需要刷新它。所以它们是不同的,一个不能替代另一个。