Elektrische Spannung (Selektionen)
Nach der bekannten Formel U = R * I werden Spannung (U [Volt]), Widerstände (R [Ohm, ?]) und Stromstärken (I [Ampère]) umgerechnet. Schreiben Sie ein Programm, bei dem der Anwender wahlweise zwei der drei Zahlen aus der Formel eingeben kann. Für die gesuchte Größe soll der Anwender ein Fragezeichen (?) eingeben. Das Programm berechnet dann die dritte Zahl; diejenige, bei der der Anwender das Fragezeichen eingegeben hat.
Beispiel:
U := 240
R := ?
I := 2.5
Resultat R = 96 Ohm
0 Kommentare
6 Lösung(en)
/********** File: spannung.xhtml *******************/
<?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>Umrechner elektrischer Widerstand</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="spannung.css" />
<script type="text/javascript" src= "helper.js" ></script>
<script type="text/javascript" src= "spannung.js"></script>
</head>
<body onload="initialize()">
<h1>Umrechner elektrischer Widerstand</h1>
<p>Umrechner von Stromspannung (Volt), Stormstärke (Ampère) und elektrischen Widerständen (Ohm).</p>
<p>Nach der Eingabe von zwei Größen kann die dritte mit <i>Berechnen</i> evaluiert werden.</p>
<table>
<tr>
<td id="spannungLabel" class="lbl">Spannung [U, Volt]: </td>
<td><input id="spannungField" type ="text" value="" onkeyup="entryCheck()" /></td>
</tr>
<tr>
<td id="staerkeLabel" class="lbl">Stomstärke [I, Ampère]: </td>
<td><input id="staerkeField" type ="text" value="" onkeyup="entryCheck()" /></td>
</tr>
<tr>
<td id="widerstandLabel" class="lbl">Widerstand [R, Ohm]: </td>
<td><input id="widerstandField" 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>
/**** FILE: spannung.js *****/
/***********************************************
* Modul: 307
* Autor: philipp gressly
* Datum: Mai 2010 (nach einer Version 2009)
***********************************************/
/* Initialize: Disable buttons, empty fields and set Default Color*/
function initialize() {
document.getElementById("spannungField") .value = "";
document.getElementById("staerkeField") .value = "";
document.getElementById("widerstandField") .value = "";
setButtonState("", "", "");
setLabelColors();
}
/* Check on every keyUp-Event ...*/
function entryCheck() {
var spannung = document.getElementById("spannungField") .value;
var staerke = document.getElementById("staerkeField") .value;
var widerstand = document.getElementById("widerstandField").value;
alertUserOnIllegalEntry(spannung, staerke, widerstand);
setLabelColors();
setButtonState(spannung, staerke, widerstand);
}
function setButtonState(spannung, staerke, widerstand) {
var submitButton = document.getElementById("submit");
var resetButton = document.getElementById("reset");
submitButton.disabled = ! isFormSubmitable(spannung, staerke, widerstand);
resetButton.disabled = ! isFormResetable (spannung, staerke, widerstand);
}
/* Alert wrong entries and set label colors. */
function alertUserOnIllegalEntry(spannung, staerke, widerstand)
{
alertWrongEntry(spannung, "Spannung")
alertWrongEntry(staerke, "Stromstärke");
alertWrongEntry(widerstand, "Widerstand");
}
/* set colors for all labels */
function setLabelColors() {
setLabelColor("spannung");
setLabelColor("staerke");
setLabelColor("widerstand");
}
/* color a single label according to its value.
* See "dichte.css".
*/
function setLabelColor(type) {
label = document.getElementById(type + "Label");
value = document.getElementById(type + "Field").value;
if("" == value) { class = "empty"; }
else if(isNumericalValue(value)) { class = "ok"; }
else if(isOKWhileEntering(value)) { class = "entering"; }
else { class = "illegal"; }
label.setAttribute("class", "entry_" + class);
}
/**
* check, if fields are OK (ready to submit).
* In our case: check, if exactly two (2) fields are
* filled in.
*/
function isFormSubmitable(spannungTxt, staerkeTxt, widerstandTxt) {
var okCount = 0
if(isNumericalValue(spannungTxt)) okCount = okCount + 1;
if(isNumericalValue(staerkeTxt)) okCount = okCount + 1;
if(isNumericalValue(widerstandTxt)) 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(u, i, r) {
return ("" != u) || ("" != i) || ("" != r);
}
/* The calculation takes place */
function submitClick() {
var spannung = document.getElementById("spannungField" ).value;
var staerke = document.getElementById("staerkeField").value;
var widerstand = document.getElementById("widerstandField" ).value;
if(! isNumericalValue(spannung)) {
showResult(staerke * widerstand, "Spannung", "Volt");
} else if (! isNumericalValue(widerstand)) {
showResult(spannung / staerke, "Widerstand", "Ohm");
} else if (! isNumericalValue(staerke)) {
showResult(spannung / widerstand, "Stromstärke", "Ampère");
}
}
/* 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
}
/********** File: spannung.css ***************/
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;
}
/************* File: helper.js **************/
/**
* 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) {
window.alert("Tag ID: " + tagID)
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; }
import java.util.*;
/**
* ElektrischeSpannung
*
* - ohne Methoden (Unterprogramme)
* - keine Abfrage / kein Abfangen von unzulässigen Eingaben
*
* @version 1.0 vom 24.04.2011
* @author HEMS (tmxmaster)
*/
public class ElektrischeSpannung{
/**
* Konstruktor mit dem HAUPTPOGRAMM
*/
public ElektrischeSpannung(){
Scanner sc = new Scanner(System.in);
String erg = "";
// Eingabe
System.out.print("U=");
String u = sc.next();
System.out.print("R=");
String r = sc.next();
System.out.print("I=");
String i = sc.next();
// Verarbeitung
if(u.equals("?")){
double strom = Double.valueOf(i);
double widerstand = Double.valueOf(r);
erg = "Resultat U = " + strom * widerstand + " V";
}
if(i.equals("?")){
double spannung = Double.valueOf(u);
double widerstand = Double.valueOf(r);
erg = "Resultat I = " + spannung / widerstand + " A";
}
if(r.equals("?")){
double spannung = Double.valueOf(u);
double strom = Double.valueOf(i);
erg = "Resultat R = " + spannung / strom + " Ohm";
}
// Ausgabe
System.out.println(erg);
}
/**************************************************
* Methoden
**************************************************/
/**
* main-Methode
* @param args Argumente als Liste, die beim Programmaufruf übergeben
* werden können. Die Übergabe ist optional.
*/
static public void main(String[] args) {
// Objektaufruf
ElektrischeSpannung es = new ElektrischeSpannung();
}
// Ende Methoden
}
Lösung von: Jürgen Mang (Heinrich-Emanuel-Merck-Schule Darmstadt)
print('* Für die gesuchte Größe ein ? eingeben.')
U = input('Spannung in Volt: ')
R = input('Wiederstand in Ohm: ')
I = input('Stromstärke in Ampere: ')
if U == '?':
U = int(R) * int(I)
print('\nDie Spannung beträgt:', U, 'Volt')
if R == '?':
R = int(U) / int(I)
print('\nDer Wiederstand beträgt:', R, 'Ohm')
if I == '?':
I = int(U) / int(R)
print('\nDie Stromstärke beträgt:', I, 'Ampere')
Lösung von: Alex Groeg (Freies Lernen)
// NET Core 3.x
using System;
using static System.Console;
namespace CS_MDL_CORE_Spannung
{
class Program
{
private const int RundenAufStellen = 2;
static void Main(string[] args)
{
(int t, double v) u, r, i;
do
{
WriteLine("\nBitte 2 von 3 Werten eingeben.\n");
u = GetValue("Spannung (Volt)");
r = GetValue("Widerstand (Ohm)");
i = GetValue("Stromstärke (Ampere)");
} while (u.t + r.t + i.t != 2);
if (u.t == 0) WriteLine($"\nSpannung: {Math.Round(r.v * i.v, RundenAufStellen)} Volt");
if (r.t == 0) WriteLine($"\nWiderstand: {Math.Round(u.v / i.v, RundenAufStellen)} Ohm");
if (i.t == 0) WriteLine($"\nStromstärke: {Math.Round(u.v / r.v, RundenAufStellen)} Ampere");
static (int t, double v) GetValue(string s)
{
Write($"{s}: ");
return (double.TryParse(ReadLine(), out var v) ? 1 : 0, v);
}
}
}
}
Lösung von: Jens Kelm (@JKooP)
/************************************************\
| benötigt ein objekt mit zwei der drei optionen |
| • i (stromstärke), |
| • u (spannung), |
| • r (widerstand) |
| gibt die fehlende option mit einheit zurück |
\************************************************/
function ohmsLaw(opts) {
switch (true) {
case !opts.i: return [opts.v / opts.r, 'A'];
case !opts.v: return [opts.r * opts.i, 'V'];
case !opts.r: return [opts.v / opts.i, '?'];
// wenn in der letzten zeile ein Omega (statt ?)
// steht, ist diese website endlich im aktuellen
// jahrtausend angekommen.
}
}
// ausgabe
console.log ( ohmsLaw({v: 44, i: 33}).join(' ') );
console.log ( ohmsLaw({v: 44, r: 50}).join(' ') );
console.log ( ohmsLaw({i: 36, r: 50}).join(' ') );
Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)
// C++ 20 | VS-2022
#include <iostream>
#include <string>
#include <optional> // c++ 17!
#include <Format> // C++ 20!
#include <vector>
#include <array>
template<class T>
class Konverter {
const T volt_, ohm_, ampere_;
public:
Konverter(std::optional<T> volt = std::nullopt, std::optional<T> ohm = std::nullopt, std::optional<T> ampere = std::nullopt)
: volt_{ *volt }, ohm_{ *ohm }, ampere_{ *ampere } {
// Anzahl der Parameter überprüfen
std::array<std::optional<T>, 3> arr{ volt, ohm, ampere };
if (std::count_if(arr.begin(), arr.end(), [](auto x) { return x == NULL; }) > 1)
throw std::invalid_argument("Fehler - Mindestens 2 Parameter eingeben!");
}
const T spannung() const noexcept {
return !volt_ ? ohm_ * ampere_ : volt_;
}
const T widerstand() const noexcept {
if (!ampere_) return 0; // Div0 abfangen
return !ohm_ ? volt_ / ampere_ : ohm_;
}
const T stromstaerke() const noexcept {
if (!ohm_) return 0; // Div0 abfangen
return !ampere_ ? volt_ / ohm_ : ampere_;
}
friend std::ostream& operator<<(std::ostream& os, const Konverter& k) {
if (!k.volt_) std::cout << std::format("{} Ampere, {} Ohm -> {} Volt\n", k.ampere_, k.ohm_, k.spannung());
else if (!k.ohm_) std::cout << std::format("{} Volt, {} Ampere -> {} Ohm\n", k.volt_, k.ampere_, k.widerstand());
else if (!k.ampere_) std::cout << std::format("{} Volt, {} Ohm -> {} Ampere\n", k.volt_, k.ohm_, k.stromstaerke());
return os;
}
};
int main() {
try {
std::vector<Konverter<float>> kon{
{ 44, NULL, 33 }, // 1.3333 Ohm
{ 44, 50, NULL }, // 0,88 Ampere
{ NULL, 50, 36 }, // 1800 Volt
//{ NULL, NULL, 33 } // erzeugt Fehler (mind. 2 Parameter)
//{ NULL, NULL, NULL } // dito
};
for (const auto& k : kon)
std::cout << k << "\n";
}
catch (const std::exception& e) {
std::cerr << e.what() << "\n";
}
}
Lösung von: Jens Kelm (@JKooP)
Verifikation/Checksumme:
- 44 Volt, 33 Ampère -> 1.333 Ohm
- 44 Volt, 50 Ohm -> 0.8800 Ampère
- 36 Ampère, 50 Ohm -> 1800 Volt
Aktionen
Neue Lösung hinzufügen
Bewertung
Durchschnittliche Bewertung:
Meta
Zeit: | 1 |
Schwierigkeit: | k.A. |
Webcode: | 43b5-76us |
Autor: | Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch) |