我需要编写代码来打印排序随机数组中的第一个和第三个四分位数。我不知道如何避开它。有什么帮助吗?如果您需要对代码进行任何澄清,请询问。谢谢
如果你能找到median((函数不起作用的原因,我将不胜感激。我认为它陷入了无限循环。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#define TABLE_SIZE 20
#define HISTOGRAM_SIZE 9
int tablica[TABLE_SIZE];
int histogram[HISTOGRAM_SIZE];
void wylosuj_tablice() //creates and randomizes the array
{
int i;
srand(time(0));
for(i=0;i<TABLE_SIZE;i++)
{
tablica[i]=(rand()%HISTOGRAM_SIZE);
}
}
void czysc_histogram() //cleans histogram
{
int i;
for(i=0; i<HISTOGRAM_SIZE; i++) {
histogram[i] = 0;
}
}
void tworz_histogram() //counts from 0 to 8
{
int i;
czysc_histogram();
for(i=0; i<TABLE_SIZE; i++) {
histogram[tablica[i]]++;
}
}
void wyswietl_histogram() // shows histogram from -4 to 4
{
int i;
for(i=0; i<HISTOGRAM_SIZE; i++) {
printf("Liczba %d: %dn", i-4 /* <== */, histogram[i]);
}
}
void wyswietl_tablice() //shows the sorted array from -4 to 4
{
int i;
for(i=0; i<TABLE_SIZE; i++) {
printf ("tablica[%d]=%dn", i, tablica[i]-4 /* <== */);
}
}
float median() {
int temp;
int i, j;
for (i=0; i<HISTOGRAM_SIZE-1; j++) {
for(j=i+1; j<HISTOGRAM_SIZE; j++) {
if(tablica[j] < tablica[i]) {
//replaces elements
temp = tablica[i];
tablica[i] = tablica[j];
tablica[j] = temp;
}
}
}
if (HISTOGRAM_SIZE%2==0) {
//if there are 2 even numbers then it return mean from them
int wynik1 = ( (tablica[HISTOGRAM_SIZE/2] + tablica[HISTOGRAM_SIZE/2 -1]) /2.0);
printf("%d", wynik1);
} else {
//if there isn't then it gives the middle one
int wynik2 = tablica[HISTOGRAM_SIZE/2];
printf("%d", wynik2);
}
}
int main()
{
wylosuj_tablice(); //executes voids
wyswietl_tablice();
tworz_histogram();
wyswietl_histogram();
median();
return 0;
}
不确定什么是"四分位数";在这里像这样的东西?
void printQuartile(int quartile)
{
wylosuj_tablice(); // To produce the data
int i, start, end;
switch(quartile) {
case 1: start = 0; end = TABLE_SIZE / 4; break;
case 2: start = TABLE_SIZE / 4; end = TABLE_SIZE / 2; break;
case 3: start = TABLE_SIZE / 2; end = (TABLE_SIZE / 4) * 3; break;
case 4: start = (TABLE_SIZE / 4) * 3; end = TABLE_SIZE; break;
default: return;
}
for(i= start; I<end; i++) {
printf ("tablica[%d]=%dn", i, tablica[i]-4);
}
}
printQuartile(1);
printQuartile(3);
输出:
tablica[0]=-4
tablica[1]=4
tablica[2]=2
tablica[3]=-1
tablica[4]=2
tablica[10]=-1
tablica[11]=3
tablica[12]=1
tablica[13]=1
tablica[14]=4