填充阵列H E L P。?! [英] Filling Array H E L P.?!
问题描述
我已经编写了一个代码,它将使用函数来计算最大值,最小值,索引值,总和值。平均。 !!
P R O B L E M:当我正在填充阵列时,它不会停在10&结果是不可预测的..
任何建议都将被赞赏.. ??
Hi, I''ve write a code that will use functions to compute maximum, minimun, index, sum & average. !!
P R O B L E M: While i''m filling the array, it will not stop at 10 & The Result is Unpredictable..
Any suggestions will be appreciated..??
// a r r a y.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdlib.h"
#include <iostream>
using namespace std;
void fill(int a[], int length)
{
for (int i = 0; i < length; i++)
{
cout << "Element #" << i+1 << endl;
cin >> i;
a[i] = i;
}
}
void print(int a[], int length)
{
cout << "A R R A Y Of 10 Elements .." << endl;
for (int j = 0; j < length; j++)
{
cout << a[j] << " | ";
}
}
void min_max(int a[], int length)
{
int min = a[0];
int max = a[0];
int min_index=0, max_index=0;
for (int k = 0; k < 10; k++)
{
if (min > a[k])
{
min = a[k];
min_index ++;
}
else
{
max = a[k];
max_index ++;
}
}
cout << '\n';
cout<<"Maximum number is: "<< max <<endl;
cout << "Max_Index: " << max_index << endl;
cout<<"Minimum number is: "<< min <<endl;
cout << "Min_Index: " << min_index << endl;
}
void sum_avg(int a[], int length)
{
int sum = 0;
for (int i = 0; i < length; i++)
{
sum = sum + a[i];
}
cout << "Mean: " << sum << endl;
int avg = sum/length;
cout << "Median: " << avg << endl;
}
int main()
{
const int length = 10;
int label[length];
fill(label, length);
print(label, length);
sum_avg(label, length)
min_max(label, length);
system("pause");
return 0;
}
推荐答案
void fill(int a[], int length)
{
for (int i = 0; i < length; i++)
{
cout << "Element #" << i+1 << endl;
cin >> i;
a[i] = i;
}
}
我使用in for循环的值,你使用相同的i值CIN(输入)。尝试:
Value i using in for loop and you use same i value in cin(input). Try:
int input;
cin >> input;
a[i] = input;
缺失;
Missing ;
sum_avg(label, length)
计算无法正常工作:
Calculation can not work correct:
int avg = sum/length;
cout << "Median: " << avg << endl;
结果和计算应该浮动或加倍。
变量我用于不同的事情,改变至:
Result and calculation should bei float or double.
Variable i used for different things, change to:
cin >> num;
a[i] = num;
除了在其他解决方案中提到的所有错误之外,最大值的计算也是错误的。
在else部分中,必须添加一个条件以确保该值实际上是最大值。如果某个值不是给定点的最小值,则可能不是最大值。
In addition to all errors mentionned in other solutions, the computation of the maximum is also incorrect.
Inside the else part, a condition must be added to ensure that the value is actually the maximum. If a value is not the minimum at a given point it might not be the maximum.
//...
else if (max < a[k]) { /* code corrected according to other solution here */ }
如果以自然方式指定条件,通常会更容易阅读。
Usually it is somewhat easier to read if the condition is specified in the natural way.
if (a[k] > max) { }
作为旁注,这是一个非常糟糕的主意将您的变量命名为min或max,这些名称是几年前流行的宏名称...
As a side note, it is a very bad idea to name your variable either min or max as these names where popular macro name a few years ago...
这篇关于填充阵列H E L P。?!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!