Я вызываю функции для получения массива от пользователя и для управления этим массивом. Моя проблема в том, что я пытаюсь получить 10 целых чисел от пользователя. После ввода 10 целых чисел в конец моего массива автоматически добавляется другое случайное целое число (возможно, ячейка памяти?). Как вы можете видеть, 2686672 был добавлен богами. Я не уверен, где моя проблема.массив возвращает дополнительное значение
мой вывод фактически указан в верхней части кода. Я попытался опубликовать рис. Вывода, но я новичок, поэтому мне не разрешено это делать.
The values of the array as entered are: 1 2 3 4 5 6 7 8 9 10 2686672
The values of the sorted array are: 1 2 3 4 5 6 7 8 9 10 2686672
The largest number in the set is 2686672
The smallest number in the set is 1
The average of the number set is 244247.906250
The standard deviation of the number set is 244242.406250
10
Код:
// include libraries
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// declare functions
int max (int count, int array[]);
int min (int count, int array[]);
int getArray (int array[]);
float stDev (int count, int array[]);
float avg (int count, int array[]);
void printArray (int count, int array[]);
void sortArray (int count, int array[]);
int main()
{
// declare variables and arrays
int count = 10;
int array[count];
// Give user instructions
printf("Please enter an integer followed by the enter key.\n");
printf("User input will halt after ten integers, \nor if a number less than zero is entered.\n");
count = getArray(array); // call function to get user input
printf("The values of the array as entered are: ");
printArray (count, array); // call function to print array as it was entered
sortArray (count, array); // call function to sort the array
printf("The values of the sorted array are: ");
printArray (count, array); // call function to print the sorted array
printf("The largest number in the set is %d\n", max (count, array)); // call function and print the max value
printf("The smallest number in the set is %d\n", min (count, array)); // call function and print the min value
printf("The average of the number set is %f\n", avg(count, array)); // call function and print the average value
printf("The standard deviation of the number set is %f\n", stDev (count, array)); // call function and print the standard deviation
printf("%d",count);
return 0;
}
//****************** FUNCTIONS *************************
/*
Function name: getArray
Inputs: The address array[0]
Outputs: Integers entered for the array. Up to 10 integers
Description: This function gets user values for the array for up to 10 separate integers.\
If a negative number, that will be the last input allowed.
*/
int getArray(int array[]){
int N=10, c; // declare local variables
// for loop that places the integer input into the array
for(c=0; c<N; c++){
scanf("%d", &array[c]); // place input into array location for that particular loop
// if a negative number is entered, force for loop end
if (array[c]<0)
N=c;
}
return c; // return the # of integers entered
}
/*
Function name: avg
Inputs: pointers for array and the number if integers in the array
Outputs: The average value of the array contents
Description: This function serves to take the individual integers in the array, add them
all together, and divide by the number of integers i.e. find the mean value
of the array.
*/
float avg(int count, int array[]){
int c; // set counter to integer
float temp = 0.0; // set temp to float
// for loop that adds all the integers in the array
for (c=0; c<= count; c++){
temp = temp + array[c]; // add current value of the array to temp
}
temp = (temp/c); // divide added integers by the number of integers
return temp; // return the mean value of the array
}
/*
Function name: max
Inputs: pointers for array and the number if integers in the array
Output: the max value of the integers in the array
Description: This function serves to find the maximum value of the array
by comparing every integer to the current maximum.
*/
int max (int count, int array[]){
int temp = array[0], c; // declare variables and set the first integer of the array to max
// for loop to compare current max to current integer
for (c=1; c<= count; c++){
// if the integer at the current array address is larger than the current max, replace it
if (array[c] > temp)
temp = array[c];
}
return temp; // return max value of the array
}
/*
Function name: min
Inputs: pointers for array and the number if integers in the array
Output: the min value of the integers in the array
Description: This function serves to find the minimum value of the array
by comparing every integer to the current minimum.
*/
int min (int count, int array[]){
int temp = array[0], c; // set the first integer in the array to minimum
// for loop that compares current integer to current min
for (c=1; c<= count; c++){
//if integer at current array address is less than the current min, replace it
if (array[c] < temp)
temp = array[c];
}
return temp; // return the minimum integer value of the array
}
/*
Function name: stDev
Inputs: pointers for array and the number if integers in the array
Output: the standard deviation of the integers in the array
Description: This function serves to find the standard deviation of the array
by comparing every integer to the mean value. The differences are
squared and added together. Then the square root of the total is taken
which is the standard deviation
*/
float stDev (int count, int array[]){
float temp = 0.0, average; // declare variables as float
int c; // declare counter as int
average = avg(count, array); // call function to get average value of the array integers
// for loop that compares the values of every integer to the mean, squares them, and adds them together
for (c=0; c< count; c++){
temp = pow(average - array[c], 2) + temp;
}
temp = sqrt(temp/c); // take the square root of the total to find standard deviation
return temp; // return the standard deviation of the array integers
}
/*
Function name: printArray
Inputs: pointers for array and the number if integers in the array
Output: prints the array
Description: This function serves to print the integer values of the array
*/
void printArray (int count, int array[]){
int c; // set counter to integer
// for loop that prints the integer at the current array address prescribed by the for loop
for (c=0; c<= count; c++){
printf("%d ", array[c]); // print the individual integers
}
printf("\n"); // new line
}
/*
Function name: sortArray
Inputs: pointers for array and the number if integers in the array
Output: the integers in the array in order from lowest to highest
Description: This function serves to put the values of the array in
order from lowest to highest
*/
void sortArray (int count, int array[]){
int temp, c, d, cc; // declare variables and counters to integer
// primary for loop that makes the secondary loop run as many times as the array has values
for (c=0; c<= count; c++){
// for loop that compares side by side values for increasing values, if they are not increasing, swap them
for (cc=0; cc< count; cc++){
d= cc+1; // set d to be one memory location higher than the the current counter value
// if the integers are not in increasing order, swap them
if (array[cc] > array[d]){
temp = array[d];
array[d] = array[cc];
array[cc] = temp;
}
}
}
}
Заранее спасибо за вашу помощь!
Почему 'getArray' не принимает' count' в качестве аргумента, как и все остальные функции? – Barmar
Его набор таким образом, потому что функция может изменить значение счетчика, если введено отрицательное число. Это показалось мне логичным, и теперь это работает, когда я изменил настройки для циклов на «c