Глава 3
Задача 3.13 "Гистограмма. "
Задание 3
б) установка соответствия между значениями функции sin x и значениями температур от 0 до 90 градусов Цельсия.
Решение
Изменим предыдущую версию программы. В качестве второго параметра функции bar() поместим выражение:
Math.sin(Math.toRadians(90))
Это выражение состоит из двух функций. Первая функция Math.sin() вычисляет синус угла выраженный в радианах, а чтобы определить радианы, воспользуемся тоже готовой функцией Math.toRadians(90) в параметре которой можно указать угол в градусах.
Вот как может выглядеть вызов функции bar в главной программе:
Hist.bar(year*10, Math.sin(Math.toRadians(year*10))*50);
Код программы:
class Histogram {
Histogram() {
HistGraf Hist = new HistGraf (9, 30);
// The headings
System.out.println(" Histogram of temperature Celsius to Sinus");
System.out.println("===================================");
System.out.println("");
System.out.println("Radians \t \t Sinus");
// Display a bar for each year and then the final axis
for (int year = 0; year <= Hist.label; year++) {
Hist.bar(year*10, Math.sin(Math.toRadians(year*10))*50);
}
Hist.axis ();
}
public static void main (String [] args) {
new Histogram ();
}
}
class HistGraf{
int label;
int h;
//----- constructor
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+" grad C \t|");
int stop = (int) Math.round(h);
for (int star = 0; star < stop; star++)
System.out.print('*');
System.out.println(" " + (double) h/100);
}
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 Sinus");
}
//=================================
} //end class HistFraf
Результат :
Назад |
Начало урока |
Вверх |
Вперед
Содержание