Глава 3
Задача 3.14 "Дни рождения "
Если вы выполнили задание 3.13, нанесите на гистограмму значения для групп из 10, 20 ... 50 человек.
Решение 3
Код программы:
import java.text.*;
import javagently.*;
import java.util.*;
import java.io.*;
class Birthdays {
Birthdays () {
HistGraf Hist = new HistGraf (60, 30);
// The headings
System.out.println("");
System.out.println(" Probably of coincidence of Birthday ");
System.out.println("===================================");
System.out.println("Peoples \t \t Probably");
// Display a bar for each year and then the final axis
for (int year = 10; year <= Hist.label; ) {
Hist.bar(year, Proba(year)*50 );
year = year+10;
}
Hist.axis ();
}
// All programs must have a main method
public static void main (String [ ] args) {
// Start the program running from its constructor
new Birthdays();
}
double Proba(int n){
int m = 365;
double k = 1;
double p = 0;
for(int i=0; i < n; i++){
k = k*(m-i)/m;
}
p = 1 - k;
return p;
}
}
class HistGraf{
int label;
int h;
HistGraf (int l, int c) {
label = l;
h = c;
}
void bar(int label, double h) {
// Draws a single histogram bar labelled
// with the years and consisting of the given
// number of stars
System.out.print(label+" peoples \t|");
int stop = (int) Math.round(h);
for (int star = 0; star < stop; star++)
System.out.print('*');
// System.out.println(" " + (double) h/100);
System.out.println(" " + Stream.format((double) h*2,3,2));
}
void axis () {
// Draws a horizontal axis with ticks+1 divisions
// labelled in steps of 10. Each division is 10
// characters wide.
int ticks = 5;
// Print the line
System.out.print("\t\t\t");
for (int line = 0; line < ticks*10; line++)
System.out.print("=");
System.out.println("=");
//Print the ticks
System.out.print("\t\t\t");
for (int n = 0; n < ticks; n++)
System.out.print("+ ");
System.out.println('+');
// Label the ticks, including the last one
System.out.print("\t\t\t");
for (int n = 0; n <= ticks; n++)
System.out.print(n*20 + " ");
System.out.println();
// Label the whole axis
System.out.println("\t\t\t\t percent");
}
} //end class HistFraf
Результат :
Назад |
Начало урока |
Вверх |
Вперед
Содержание