Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Quadratische Gleichung (Anweisungen und Abfolgen)

Schreiben Sie ein Programm, das die Lösungen x1 und x2 der Quadratischen Gleichung

ax2 + bx + c = 0

ausgibt.

Die beiden Lösungen berechnen sich wie folgt:

x1 = (- b + sqrt(b2 - 4ac)) / (2a)

x2 = (- b - sqrt(b2 - 4ac)) / (2a)

Die Quadratwurzel wird meist mit der Funktion sqrt() bezeichnet.

Der Anwender gibt a, b und c ein und es werden ihm die beiden Lösungen präsentiert.

4 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

Kommentare (4)

gressly 11. November 2014 06:56   reply report
gouchi4th
Hallo Herr Gressly,

sie haben sicherlich nicht gemerkt, aber es gibt einige Fehler in Ihrer vorgeschlagenen Lösung.

In Ihrer Utility-Klasse (Input), bei den Methoden "public static byte inputByte(question. byte.class){...}", "public static short inputShort(question, short.class){...}",.....

Der Fehler lautet: "Cannot cast from Number to byte". Das casting von Number zu byte ist nicht möglich, da die Methode "inputNumber vom Type Number ist.

Daher es müssen entsprechende Wrapper-Klassen her.

Mit freundlichen Grüßen

Herr Houssein Fofana

PS: Das KISS (Keep it short and simple)-Prinzip im Auge behalten.

Seltsam, ich muss dem Problem nachgehen. Möglicherweise ein Problem der verschiedenen Java-Versionen:

Bei meinem Java 1.8.0 geht das wunderbar. Ich habe sogar folgenden Test laufen lassen:

byte b = inputByte("Gib ein Byte ein: ");
System.out.println("Byte gelesen: " + b);
gressly 8. November 2014 13:37   reply report
Hilli
Die Loesungsformeln fuer x1 und x2 wie oben angegeben sind unvollstaendig. Es fehlt noch ein '/ 2a' jeweils.

stimmt, das / (2a) hatte ich der Klasse einfach an die Tafel geschrieben, beim Abtippen aber vergessen.

Besten Dank für den Hinweis.
Hilli 23. Oktober 2014 04:08   reply report
Die Loesungsformeln fuer x1 und x2 wie oben angegeben sind unvollstaendig. Es fehlt noch ein '/ 2a' jeweils.
gouchi4th 14. Oktober 2014 14:53   reply report
Hallo Herr Gressly,

sie haben sicherlich nicht gemerkt, aber es gibt einige Fehler in Ihrer vorgeschlagenen Lösung.

In Ihrer Utility-Klasse (Input), bei den Methoden "public static byte inputByte(question. byte.class){...}", "public static short inputShort(question, short.class){...}",.....

Der Fehler lautet: "Cannot cast from Number to byte". Das casting von Number zu byte ist nicht möglich, da die Methode "inputNumber vom Type Number ist.

Daher es müssen entsprechende Wrapper-Klassen her.

Mit freundlichen Grüßen

Herr Houssein Fofana

PS: Das KISS (Keep it short and simple)-Prinzip im Auge behalten.

12 Lösung(en)

let xn op a b c =
    op -b (sqrt (pown b 2 - 4.0 * a * c))
        
let ergenzung a b c=
   printfn "x1 = %f und x2 = %f" 
        (xn (-) a b c) (xn (+) a b c)
   
ergenzung 1.0 10.0 25.0
                

Lösung von: Vural Acar ()

import static eu.gressly.io.utility.Input.*;

public class QuadratischeGleichung {

	public static void main(String[] args) {
		new QuadratischeGleichung().top();
	}


	void top() {
		setAddQuestion("Bitte %s der quadratischen Gleichung ax2+bx+c=0 eingeben: ");
		double a  = inputDouble("a");
		double b  = inputDouble("b");
		double c  = inputDouble("c");
		double d  = Math.sqrt(b*b - 4*a*c);
		double x1 = (-b + d) / (2*a);
		double x2 = (-b - d) / (2*a);
		System.out.println("x1 = " + x1);
		System.out.println("x2 = " + x2);
	}
}
 // end of class QuadratischeGleichung

/************************************************************/

// Mit folgender Input-Hilfsklasse:
package eu.gressly.io.utility;

import java.util.Scanner;

/**
 * Input Methods like the BASIC INPUT (or c's scanf()). 
 * 
 * Because Java has no simple console input, I added this functions to
 * my library.
 * Simply import
 * <code>import static eu.gressly.io.utility.Input.*</code>
 * and then use
 * <code>int x = inputInt("Please enter x: ");</code>
 * 
 * @version 0.1 (Oct 8, 2014)
 * @author Philipp Gressly Freimann 
 *         (philipp.gressly@santis.ch)
 */

public class Input {

	private static Scanner sc = new Scanner(System.in);

	/**
	 * @see setAskAgain();
	 */
	private static boolean askAgain = true;


	/**
	 * @see setAddQuestion()
	 */
	private static String addQuestion = "";


	/**
	 * @see setNumberFormatError()
	 */
	private static String numberFormatErrorMessage = "Error entering a number.";


	/**
	 * If askAgain is false, the user is asked only once.
	 * Entering newlines do not ask the user again showing the "question".
	 * default: true
	 * @param askAgain
	 */
	public static void setAskAgain(boolean askAgain) {
		Input.askAgain = askAgain;
	}


	/**
	 * If the programmer only wants to ask for a "value" instead of a
	 * "question", this text has to be set.
	 * Typically: setAddQuestion("Please enter the value for %s : ");
	 * "%s" is replaced by the programmers question afterwards.
	 * @param addQuestion has to contain a %s, where the parameter name
	 *        sohuld be replaced.
	 */
	public static void setAddQuestion(String addQuestion) {
		if(addQuestion.indexOf("%s") < 0) {
			addQuestion = addQuestion + "%s";
		}

		Input.addQuestion = addQuestion;
	}


	/**
	 * This message is shown to the user, if she/he does not enter a
	 * number while using "intputInt()" or "inputDouble()".
	 * @param errorMessage to show on NumberFormatExceptions.
	 */
	public static void setNumberFormatError(String errorMessage) {
		Input.numberFormatErrorMessage = errorMessage;
	}


	private static void quest(String question) {
		if(null == addQuestion || addQuestion.length() < 1) {
			System.out.println(question);
			return;
		}
		System.out.printf(addQuestion, question);
	}


	public static String inputString(String frage) {
		String eingabe = "";
		if(! askAgain) {
			quest(frage);
		}
		while(eingabe.length() < 1) {
			if(askAgain) {
				quest(frage);
			}
			eingabe = sc.nextLine().trim();
		}
		return eingabe;
	}



	public static byte inputByte(String question) {
		return (byte) inputNumber(question, byte.class);
	}


	public static short inputShort(String question) {
		return (short) inputNumber(question, short.class);
	}


	public static int inputInt(String question) {
		return (int) inputNumber(question, int.class);
	}


	public static long inputLong(String question) {
		return (long) inputNumber(question, long.class);
	}


	public static float inputFloat(String question) {
		return (float) inputNumber(question, float.class);
	}


	public static double inputDouble(String question) {
		return (double) inputNumber(question, double.class);
	}



	/**
	 * Input a single char.
	 * Any further chars on the same line are ignored.
	 */
	public static char inputChar(String question) {
		return inputString(question).trim().charAt(0);
	}


	/**
	 * Returns true, if the users input does not start with the letter 'n'.
	 * @param question any Question having "yes" or "no" as answer.
	 * @return true iff the users answer does not start with an "n".
	 */
	public static boolean inputBoolean(String question) {
		return 'n' != inputString(question).trim().toLowerCase().charAt(0);
	}


	private static String inputString() {
		String eingabe = "";
		while(eingabe.length() < 1) {
			eingabe = sc.nextLine().trim();
		}
		return eingabe;
	}


	private static Number inputNumber(String question, Object numberClass) {
		String answer = "";
		if(! askAgain) {
			answer = inputString(question);
		}
		while (true) {
			try {	
				if(askAgain) {
					answer = inputString(question);
				} 
				Number zahl = 0; // will be chaged soon...
				if(numberClass == byte.class) {
					zahl = Byte.parseByte(answer);
				}
				if(numberClass == short.class) {
					zahl = Short.parseShort(answer);
				}
				if(numberClass == int.class) {
					zahl = Integer.parseInt(answer);
				}
				if(numberClass == long.class) {
					zahl = Long.parseLong(answer);
				}
				if(numberClass == float.class) {
					zahl = Float.parseFloat(answer);
				}
				if(numberClass == double.class) {
					zahl = Double.parseDouble(answer);
				}
				return zahl;
			} catch (Exception ex) {
				System.out.println(numberFormatErrorMessage);
				if(!askAgain) {
					answer = inputString();
				}
			}
		}
	}

} // end of class Input
                

Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

from math import sqrt

a = float(input('Wert fuer a: '))
b = float(input('Wert fuer b: '))
c = float(input('Wert fuer c: '))

x1 = (- b + sqrt((b * b) - (4 * a * c))) / (2 * a)
x2 = (- b - sqrt((b * b) - (4 * a * c))) / (2 * a)

print('x1 =', x1, 'und x2 =', x2)
                

Lösung von: Hilli Hilli ()

import java.util.Scanner;

public class Mitternachtsformel {
	public static void main (String[ ] args) {
		
		@SuppressWarnings("resource")
		Scanner in = new Scanner(System.in);
		
		double a, b, c;																
		double Wurzel, x1, x2;														
		
		System.out.println("Gib a ein!");   									
		a = in.nextInt();
							
		System.out.println("Gib b ein!");											
		b= in.nextInt();
			
		System.out.println("Gib c ein!");											
		c = in.nextInt();
		
		Wurzel= (b*b)-(4*a*c);														
		
		if (Wurzel > 0){															
			x1 = (-b + Math.sqrt(Wurzel))/(2*a);
			x2 = (-b - Math.sqrt(Wurzel))/(2*a);
			System.out.println("Zwei Lösungen: x1 = " +x1 +" und x2 = "  +x2 );
	
		}else{
			
			if (Wurzel == 0){														
				x1 = (-b + Math.sqrt(Wurzel))/(2*a);
				System.out.println("Eine lösung: x1 = " +x1);
				}
			else System.out.println("Keine lösung!");								
			}		
	}
}
		

                

Lösung von: Butrint Pacolli ()

// eingabemaske
document.write(
   '<input type="number" value="2" id="a" onchange="compute()"><br>' +
   '<input type="number" value="-9" id="b" onchange="compute()"><br>' +
   '<input type="number" value="-18" id="c" onchange="compute()"><br>' 
);

function quadraticEquation(a, b, c) {
   return [
      (- b + Math.sqrt(b * b - 4 * a * c)) / (2 * a),
      (- b - Math.sqrt(b * b - 4 * a * c)) / (2 * a)
   ];
}

function compute() {
   console.log(quadraticEquation(
      document.getElementById("a").value,
      document.getElementById("b").value,
      document.getElementById("c").value
   ));
}
                

Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)

import scala.io.StdIn._
import scala.math._

object SqrtCalc extends App {
println("Quadrat Funktionen 2015 Scala")
println("Gib a ein")
var a = readDouble()
println("Gib b ein")
var b = readDouble()
println("Gib c ein")
var c = readDouble()
var x1 = (- b + sqrt((b*b) - 4*(a*c))) / (2*a)
var x2 = (- b - sqrt((b*b) - 4*(a*c))) / (2*a)

println("x1 = " + x1)
println("x2 = " + x2)
}
                

Lösung von: Name nicht veröffentlicht

 class Program
    {
        static void Main(string[] args)
        {
            double a, b,c, x1, x2;
            Console.WriteLine("Geben Sie a ein: ");
            a = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Geben Sie b ein: ");
            b = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Geben Sie a ein: ");
            c = Convert.ToDouble(Console.ReadLine());

            x1 = (-b + Math.Sqrt((b * b) - (4 * a * c))) / (2 * a);
            x2 = (-b - Math.Sqrt((b * b) - (4 * a * c))) / (2 * a);

            Console.WriteLine("x1 = " + x1 + "; x2 = " + x2);            
            Console.ReadKey();


        }
    }
                

Lösung von: Py Thon ()

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double x1_calc(int a, int b, int c);
double x2_calc(int a, int b, int c);

int main (void)
{
	int a,b,c;
	char temp[100];
	double x1,x2;

	printf("Programm zur Berechnung von x1 und x2 in quadr. Gleichungen\n");
	printf("                      ax² + bx +c                          \n");
	printf("***********************************************************\n");
	printf("\n\n");
	printf("Bitte geben Sie die Zahl a ein:");
	fgets(temp, 100, stdin);
	a = atoi(temp);
	printf("Bitte geben Sie die Zahl b ein:");
	fgets(temp, 100, stdin);
	b = atoi(temp);
	printf("Bitte geben Sie die Zahl c ein:");
	fgets(temp, 100, stdin);
	c = atoi(temp);
	printf("\nDie Gleichung lautet %d*x² + %d*x + %d\n\n", a, b, c);
	x1 = x1_calc(a,b,c);
	x2 = x2_calc(a,b,c);
	printf("\n\nx1 = %lf\n", x1);
	printf("x2 = %lf\n\n\n", x2);

	return 0;
}

double x1_calc(int a, int b, int c)
{
	double result;
	double wurzel;

	wurzel = (b*b) - 4*a*c;
	if(wurzel < 0)
	{
		printf("Nur komplexe Lösung möglich!!");
		exit(0);
	}
	result = (-b + sqrt(wurzel)) /(2*a);
	return result;
}

double x2_calc(int a, int b, int c)
{
	double result;
	double wurzel;

	wurzel = (b*b) - 4*a*c;
	if(wurzel < 0)
	{
		printf("Nur komplexe Lösung möglich!!");
		exit(0);
	}
	result = (-b - sqrt(wurzel)) /(2*a);
	return result;
}
                

Lösung von: Florian Hofinger (FH Salzburg AT)

from math import sqrt
def quadratische():
    a = int(input("Geben sie einen Wert1 ein: "))
    b = int(input("Geben sie einen wert2 ein: "))
    c = int(input("Geben sie einen Wert3 ein: "))
    delta = b*b-4*a*c
    if a != 0 and b != 0 and c!=0:
        if delta < 0:
            print("Keine Antworte")
        elif delta == 0:
            x0 = -b/(2*a)
            print(x0)
        else:
            x1 = (-b + sqrt(delta))/(2*a)
            x2 = (-b - sqrt(delta))/(2*a)
            print("x1 ist", x1, "und x2 ist", x2)
        

                

Lösung von: Hermann Lallah (THM)

// C++ 20 | VS-2022
#include <iostream>

std::tuple<double, double> qrt_fun(double a, double b, double c) {
    const auto r{ [&](int i) {return (-b + i * sqrt(b * b - 4 * a * c) / 2 * a); } };
    return { r(-1), r(1) };
}

int main() {
    const auto [x1, x2]{ qrt_fun(2, 4, -6) }; // C++ 20!
    std::cout << x1 << ", " << x2 << "\n";
}
                

Lösung von: Jens Kelm (@JKooP)

// NET 7.x | C# 11.x | VS-2022
(double x1, double x2) QrtFun(double a, double b, double c) {
    var r = (int i) => -b + i * + Math.Sqrt(b * b - 4 * a * c) / 2 * a;
    return (r(-1), r(1));
}

var (x1, x2) = QrtFun(2, 4, -6);
Console.WriteLine($"x1 = {x1}; x2 = {x2}");
                

Lösung von: Jens Kelm (@JKooP)

' VBA

Function QrtFun(a#, b#, c#)
    r# = b * b - 4 * a * c
    If r < 0 Then
        s$ = "NaN"
    Else
        t# = (Sqr(r) / 2 * a)
        s$ = (-b + t)
        s = s & ", " & (-b - t)
    End If
    QrtFun = s
End Function

Sub Main()
    Debug.Print QrtFun(2, 4, -6)
End Sub
                

Lösung von: Jens Kelm (@JKooP)

Verifikation/Checksumme:

 

2x2 - 9x -18 =0 

a=2, b= -9, c= -18 

x1 = 6

x2 = -3/2 = - 1.5

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 0.25
Schwierigkeit: Leicht
Webcode: dk4s-3aeg
Autor: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen