Harmonisches Mittel (Anweisungen und Abfolgen)
Schreiben Sie ein Programm, das von zwei gegebenen Zahlen das harmonische Mittel berechnet. Zum Beispiel ist das harmonische Mittel der beiden Noten a' (= 440 Herz = Kammerton) und a" (= 880 Herz) genau die Quarte,
Das harmonische Mittel von zwei Zahlen a und b berechnet sich wie folgt:
harmonisches Mittel(a, b) = 2 \over {{1 \over a} + {1 \over b}}
Ihr Programm nimmt zwei Frequenzen a und b entgegen und gibt deren harmonisches Mittel aus.
0 Kommentare
7 Lösung(en)
/***********************************************
* Programmieraufgabe "Harmonisches Mittel" (Datei mittel.js)
* (Auch in Modul 307 verwendet)
* Autor: philipp gressly freimann
* Datum: Mai 2012 (nach einer Version 2010)
***********************************************/
/* Initialize: Disable buttons, empty fields and set Default Color*/
function initialize() {
document.getElementById("aField").value = "";
document.getElementById("bField").value = "";
setButtonState("", "");
setLabelColors();
}
/* Check on every keyUp-Event ...*/
function entryCheck() {
var a = document.getElementById("aField").value;
var b = document.getElementById("bField").value;
alertUserOnIllegalEntry(a, b);
setLabelColors();
setButtonState(a, b);
}
function setButtonState(a, b) {
var submitButton = document.getElementById("submit");
var resetButton = document.getElementById("reset");
submitButton.disabled = ! isFormSubmitable(a, b);
resetButton.disabled = ! isFormResetable (a, b);
}
/* Alert wrong entries and set label colors. */
function alertUserOnIllegalEntry(a, b)
{
alertWrongEntry(a, "a");
alertWrongEntry(b, "b");
}
/* set colors for all labels */
function setLabelColors() {
setLabelColor("a");
setLabelColor("b");
}
/* color a single label according to its value.
* See "mittel.css".
*/
function setLabelColor(type) {
label = document.getElementById(type + "Label");
value = document.getElementById(type + "Field").value;
var cls;
if("" == value) { cls = "empty"; }
else if(isNumericalValue(value)) { cls = "ok"; }
else if(isOKWhileEntering(value)) { cls = "entering"; }
else { cls = "illegal"; }
label.setAttribute("class", "entry_" + cls);
}
/**
* check, if fields are OK (ready to submit).
* In our case: check, if exactly two (2) fields are
* filled in.
*/
function isFormSubmitable(aTxt, bTxt) {
var okCount = 0;
if(isNumericalValue(aTxt)) okCount = okCount + 1;
if(isNumericalValue(bTxt)) okCount = okCount + 1;
return 2 == okCount;
}
/* check, if "txt" is a nonempty number */
function isNumericalValue(txt) {
return ("" != txt && isFinite(txt));
}
/* A value can be wrong while entering - but should not be
* alerted. E. g. To enter "-6" you have to enter "-" first,
* which is not ok.
*/
function isOKWhileEntering(value) {
return (/^(-|\+)?[0-9]*(\.[0-9]*)?$/.test(value));
}
// check Field while entering
var oldWrongTxt = ""; // Damit beim "Enter", der "Keyup" nicht nochmals abgefangen wird.
function alertWrongEntry(txt, label) {
if(! isOKWhileEntering(txt)) {
if(oldWrongTxt != txt) {
window.alert(label + " muss eine Zahl sein!");
oldWrongTxt = txt;
}
}
}
/*check, if any of the 3 Fields contains a value
* so that "reset" makes sense. */
function isFormResetable(a, b) {
return ("" != a) || ("" != b);
}
/* The calculation takes place */
function submitClick() {
var a = document.getElementById("aField").value;
var b = document.getElementById("bField").value;
showResult( 2 / ((1 / a) + (1 / b)), "Frequenz", "Herz");
}
/* Show the result in a given "output" field (id = "ausgabe") */
function showResult(value, measurand, unit) {
value = value.toPrecision(4);
resultText = "Resultat: " + measurand + " = " + value + " [" + unit + "]";
setFirstTextChild("ausgabe", resultText);
//replaceTag("ausgabe", resultText)
/* Alternativ: */
//document.getElementById("ausgabe").innerHTML = resultText
}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< mittel.xhtml >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<< Zugehöriges HTML File mit ein und Ausgabefeldern
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns="http://www.w3.org/1999/xhtml" lang="de">
<head>
<title>Berechnung des harmomischen Mittels</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel ="stylesheet" type="text/css" href="mittel.css" />
<script type="text/javascript" src= "helper.js" ></script>
<script type="text/javascript" src= "mittel.js"></script>
</head>
<body onload="initialize()">
<h1>Harmonisches Mittel</h1>
<p>Berechne das harmonische Mittel von zwei gegebene Zahlen (Herz).</p>
<p>Nach der Eingabe von zwei Größen kann das harmonische Mittel mit <i>Berechnen</i> evaluiert werden.</p>
<table>
<tr>
<td id="aLabel" class="lbl">1. Frequenz (a): </td>
<td><input id="aField" type ="text" value="" onkeyup="entryCheck()" /></td>
</tr>
<tr>
<td id="bLabel" class="lbl">2. Frequenz (b): </td>
<td><input id="bField" type ="text" value="" onkeyup="entryCheck()" /></td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="Berechnen" id="submit" onclick="submitClick()" />
<input type="reset" value="Rücksetzen" id="reset" onclick="initialize()"/>
</td>
</tr>
</table>
<p id="ausgabe"/>
</body>
</html>
***************************** helper.js ******************************
** Javascript DOM Helper Functions
**********************************************************************
/**
* Author : phi (at) gressly.ch
* Juni 2009 for modul 307 (santis training ag)
*/
/**
* Set the (first) Text child [in the tag <tag id="tagID">]
* to the given text.
*/
function setFirstTextChild(tagID, text) {
var oldTag = document.getElementById(tagID);
var txtnode = document.createTextNode(text);
if(oldTag.firstChild) {
oldTag.replaceChild(txtnode, oldTag.firstChild) }
else {
oldTag.appendChild(txtnode) }
}
/**
* Replace a Tag <tag id="tagID"> with a new <tag>
* containing a given value (text).
* The new Tag will have the same type (nodeName) as the given tag.
*/
function replaceTag(tagID, text) {
var oldTag = document.getElementById(tagID);
var tagType = oldTag.nodeName
var parentNode = oldTag.parentNode
var newTag = makeTextTag(tagType, tagID, text);
parentNode.replaceChild(newTag, oldTag); }
/*
Obige Funktion ist äquivalent zu:
document.getElementById(tagID).innerHTML = text;
*/
/**
* Helper function to generate a new paragraph-node.
*/
function makeTextTag(tag, tagID, text) {
var newTag
if(document.createElementNS) { // firefox knows createElementNS
newTag = document.createElementNS("http://www.w3.org/1999/xhtml", tag) }
else { // IE (createElementNS undefined)
newTag = document.createElement(tag) }
var txtnode = document.createTextNode(text);
newTag.setAttribute("id", tagID);
newTag.appendChild(txtnode);
return newTag;
}
******************************************* mittel.css *********************************
** CSS
***************************************************************************************
/* Philipp Gressly Freimann, Santis Training AG*/
h1 {
color: blue;
}
body {
background-color: #ddd;
}
@media print {
body {
font-family : "times new roman", Times, serif;
}
}
@media screen, handheld {
body {
font-family: Verdana, Helvetica, Arial, sans-serif;
}
}
table {
background-color: #ccc;
}
/* Colors for Labels */
.entry_ok {
color : #0A0;
}
.entry_entering {
color : #830;
}
.entry_illegal {
color : #F50;
}
.entry_empty {
color : #058;
}
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
a = float(input("A: "))
b = float(input ("B: "))
harm = 2/((1/a)+(1/b))
print ("Harmonisches Mittel aus ", a, "und ", b, " ist ", harm)
Lösung von: Py Thon ()
def harmMittel(a,b):
a = float(a)
b = float(b)
harm = round(2/((1/a)+(1/b)),2)
print "Harmonisches Mittel aus ", a, "und ", b, " ist ", harm
harmMittel(440,880)
Lösung von: Py Thon ()
"""Berechnung des harmonischen Mittels mit GUI """
"""- hier tkinter in der Version 3.2"""
import tkinter as tk
def harmMittel():
a = float (a_entry.get())
b = float(b_entry.get())
harm = round(2/((1/a)+(1/b)),2)
ergebnis.config(text = harm)
main = tk.Tk()
label = tk.Label(main, text = "Prog. zur Berechnung des harmonischen Mittels")
label.pack()
a_label = tk.Label(main, text = "1. Zahl")
a_label.pack()
a_entry = tk.Entry(main)
a_entry.pack()
b_label = tk.Label(main, text = "2. Zahl")
b_label.pack()
b_entry = tk.Entry(main)
b_entry.pack()
ergebnis = tk.Label(main, text = "Ergebnis")
ergebnis.pack()
rechne = tk.Button(main, text = "Rechne", command = harmMittel)
rechne.pack()
main.mainloop()
Lösung von: Py Thon ()
// Autor: Andy Großhennig
// Solution for task: Harmonisches Mittel (Anweisungen und Abfolgen)
#include <iostream>
using namespace std;
void calculateHarmony()
{
int iFrequency_1, iFrequency_2;
float fHarmony = 0;
cout << "Geben sie den ersten Wert ein: ";
cin >> iFrequency_1;
cout << "\nGeben sie den zweiten Wert ein: ";
cin >> iFrequency_2;
fHarmony = 2 / ((1 / (float)iFrequency_1) + (1 / (float)iFrequency_2));
cout << "\nDas Harmonische Mittel von " << iFrequency_1 << " und " << iFrequency_2 << " ist: " << fHarmony;
}
int main()
{
calculateHarmony();
cout << "\n\n";
system("Pause");
return 0;
}
Lösung von: Andy Großhennig (Bundeswehr)
# Python 3.4.2
frequenz1 = float(input('Frequenz a: '))
frequenz2 = float(input('Frequenz b: '))
harm_mittel = 2 / ((1 / frequenz1) + (1 / frequenz2))
print('\nDas harmonische Mittel betraegt', round(harm_mittel, 2))
Lösung von: Hilli Hilli ()
// eingabemaske
document.write(
'<input type="number" value="440" id="freq1" onchange="out()">' +
' Frequenz 1<br>' +
'<input type="number" value="880" id="freq2" onchange="out()">' +
' Frequenz 2'
);
function harmonicMean(a, b) {
return 2 / ((1 / a) + (1 / b));
}
function out() {
var freq1 = document.getElementById("freq1").value,
freq2 = document.getElementById("freq2").value;
console.log(harmonicMean(freq1, freq2).toFixed(2));
}
Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)
Verifikation/Checksumme:
Das Harmonische Mittel von 440 (a') und 880 (a") ist 586.67 (d").
Aktionen
Neue Lösung hinzufügen
Bewertung
Durchschnittliche Bewertung:
Meta
Zeit: | 0.25 |
Schwierigkeit: | Leicht |
Webcode: | pg23-w5ae |
Autor: | Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch) |