Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Nullstellen (Kleinprojekte)

Schreiben Sie ein Programm, dass die Nullstellen einer linearen Funktion oder einer quadratischen Funktion ausgibt.

Lineare Funktion: f(x)=a*x+b

Quadratische Funktion: f(x)=a*x2+b*x+c

Der Nutzer soll vor der Eingabe entscheiden können welchen Funktionstyp er benutzen möchte.

Danach soll der Nutzer die Parameter a, b und c eingeben(c nur bei der quadratischen Funktion) und die Nullstellen sollen daraufhin ausgegeben werden.

Hinweise:

Eine lineare Funktion hat immer eine Nullstelle, außer a=0 und b!=0(Bei a=0 und b=0 gibt es unendlich viele Nullstellen!).

Eine Quadratische Funktion hat zwei, eine oder keine Nullstellen. Es gibt mehrere Möglichkeiten die Nullstellen einer quadratischen Funktion herauszufinden(z.B. pq-Formel, Mitternachtsformel). Achten Sie darauf, dass bei nur einer Nullstelle auch nur eine ausgegeben wird und nicht zweimal die gleiche angezeigt wird.

 

0 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

10 Lösung(en)

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

float main(){

float a,b,c,x1,x2;
int typ;

printf("\nDieses Programm gibt die Nullstellen einer Funktion aus.\n\n");
printf("[1] a*x+b=0\n[2] a^2*x+b*x+c=0\n\n");
printf("Welche Gleichung?: ");
scanf("%d",&typ);
if(typ != 1 && typ != 2){
  printf("Falsche Eingabe.");
  return 0;
}
printf("\na = ");
scanf("%f",&a);
printf("b = ");
scanf("%f",&b);
if(typ == 2){
printf("c = ");
scanf("%f",&c);
}

if(typ == 1){
  x1 = (-b)/a;
  if(a == 0 && b != 0){
    printf("Die Steigung ist 0. Darum gibt es keine Nullstelle.");
  }
  if(a == 0 && b == 0){
    printf("Es gibt unendlich viele Nullstellen.");
  }else{
    printf("x: %f",x1);
  }
}

if(typ == 2){
  x1 = ((-b) + sqrtf(b*b-4*a*c))/(2*a);
  x2 = ((-b) - sqrtf(b*b-4*a*c))/(2*a);
  if((b*b-4*a*c) < 0 || 2*a == 0){
    printf("Kein Ergebnis.");
  }else{
    if(x1 == x2){
      printf("x: %f\n",x1);
    }else{
      printf("x1: %f\n",x1);
      printf("x2: %f\n",x2);
    }
  }
}
}

                

Lösung von: Fynn Koch (keine)

report  z_nullstellen.
type-pools abap.

data: null type i,
      null2 type i,
      root type i.

selection-screen begin of block b1 with frame title text-f01.
parameters linear as checkbox.
parameters quadr as checkbox.
parameters: a type i obligatory, b type i obligatory, c type i default
0.
selection-screen end of block b1.

start-of-selection.
  case abap_true.
    when linear.
      if quadr = abap_true.
        message 'Bitte für eine Funktion entscheiden!' type 'I'.
        exit.
      endif.
      if a = 0 and b = 0.
        write 'unendlich viele Nullstellen'.
      elseif a = 0 and b <> 0.
        write 'keine Nullstelle'.
      else.
        null = ( 0 - b ) /  a.
        write null.
      endif.
    when quadr.
      if linear = abap_true.
        message 'Bitte für eine Funktion entscheiden!' type 'I'.
        exit.
      endif.
      if a = 0 and b <> 0.
        null = ( 0 - c ) /  b.
        write null.
      elseif a = 0 and b = 0 and c = 0.
        write 'unendlich viele Nullstellen'.
      elseif a = 0 and b = 0 and c <> 0.
        write 'keine Nullstelle'.
      else.
        root = b * b - 4 * a * c.
        if root  < 0.
          write 'keine Nullstelle'.
        else.
          null = ( - b + sqrt( root ) ) / 2 * a.
          null2 = ( - b - sqrt( root ) ) / 2 * a.
          if null = null2.
            write null.
          else.
           write: 'erste Nullstelle: ', null, / , 'zweite Nullstelle: ',
  null2.
          endif.
        endif.
      endif.
    when others.
      message 'Bitte für eine Funktion entscheiden!' type 'I'.
      exit.
  endcase.
                

Lösung von: Name nicht veröffentlicht

/* Kotlin */
import java.lang.NumberFormatException
import kotlin.math.abs
import kotlin.math.sqrt

fun main() {
    var type: Double
    println("1: f(x)=a*x+b")
    println("2: f(x)=a*x²+b*x+c")

    do {
        type = read("Typ auswählen")
    } while (type != 1.0 && type != 2.0)

    var a = read("a")
    var b = read("b")

    if(type == 2.0 && a == 0.0) {
        type = 1.0
        a = b
        b = read("c")
    }

    when(type) {
        1.0 -> {
            if(a == 0.0 && b == 0.0) {
                println("Es gibt unendlich viele Nullstellen!")
                return
            } else if(a == 0.0 && b != 0.0) {
                println("Es gibt keine Nullstellen!")
                return
            }

            val x = -b / a
            println("x = %f".format(x))
        }

        2.0 -> {
            val c = read("c")
            val discriminant = b*b - 4*a*c

            val alpha = -b / (2*a)
            val beta = (sqrt(abs(discriminant))) / (2*a)

            if(discriminant < 0) {
                println("x1 = %f - %fi".format(alpha, beta))
                println("x2 = %f + %fi".format(alpha, beta))
            } else {
                val x1 = alpha - beta
                val x2 = alpha + beta

                if(x1 == x2) {
                    println("x = %f".format(x1))
                } else {
                    println("x1 = %f".format(x1))
                    println("x2 = %f".format(x2))
                }
            }
        }
    }
}

fun read(s: String): Double {
    print("%s: ".format(s))

    return try {
        readLine()!!.toDouble()
    } catch (e: NumberFormatException) {
        println("Fehler: Keine Zahl")
        read(s)
    }
}
                

Lösung von: Name nicht veröffentlicht

/* GOLANG */

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

func readParam(readA bool, readB bool, readC bool) (a float64, b float64, c float64, err error) {
	var read string

	if readA {
		fmt.Print("a=")
		_, err = fmt.Scanf("%s\n", &read)
		a, _ = strconv.ParseFloat(read, 64)
	}

	if readB {
		fmt.Print("b=")
		_, err = fmt.Scanf("%s\n", &read)
		b, _ = strconv.ParseFloat(read, 64)
	}

	if readC {
		fmt.Print("c=")
		_, err = fmt.Scanf("%s\n", &read)
		c, _ = strconv.ParseFloat(read, 64)
	}

	return a, b, c, err
}


func main() {
	reader := bufio.NewReader(os.Stdin)

	fmt.Println("Choose equation type:")
	fmt.Println("Type - 1 - for linear ( f(x) = a*x=b )")
	fmt.Println("Type - 2 - for quadratic ( f(x) = ax^2 + bx + c)")

	equationType, _, err := reader.ReadRune()

	if err != nil { os.Exit(1) }

	switch equationType {
	case '1':
		a, b, _, err := readParam(true, true, false)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		if a == 0 {
			if b != 0 {
				fmt.Println("No zero")
			} else {
				fmt.Println("Zero for every x")
			}
			os.Exit(0)
		} else {
			x := -b / a
			fmt.Printf("x = %f\n", x)
		}
		break
	case '2':
		a, b, c, err := readParam(true, true, true)
		if err !=  nil {
			fmt.Println(err)
			os.Exit(1)
		}

		det := math.Pow(b, 2) - 4 * a * c

		if det < 0 {
			fmt.Println("No real solutions")
		} else if det > 0 {
			fmt.Println("Two Solutions in R: ")
			x := (-b + math.Sqrt(math.Pow(b, 2) - 4 * a * c))/ (2 * a)
			fmt.Printf("%f\n", x)
			x = (-b - math.Sqrt(math.Pow(b, 2) - 4 * a * c))/ (2 * a)
			fmt.Printf("%f\n", x)
		} else {
			fmt.Println("One Solution in R: ")
			x := -b / (2*a)
			fmt.Printf("%f\n",x)
		}
	}
}
                

Lösung von: Name nicht veröffentlicht

/**
 * Eine lineare Gleichung ist ein Spezialfall einer quadratischen Gleichung ax² + bx + c 
 * <=> wenn a = 0. Eine Gleichung besitzt immer genau so viele Nullstellen, wie der Grad
 * ihrer höchsten Potenz. Die Formel zum Ermitteln der Nullstellen einer quadr. Gl. lautet:
 * {-p/2 +/- sqrt((p/2)^2 - q)} mit p = b/a und q = c/a unter der Bedingung a ? 0 .
 * 
 * @author Carsten Krahl
 */
public class Launcher {

	public static void main(String[] args) {

		double nst[] = nullstellen( -1, 1, 1 );
		
		boolean isNonLinear = nst.length == 2; // prüfe auf quadr. Funktion
		boolean nst_exists  = (isNonLinear) && // Gibt es eine od. mehrere Nullstellen?
				!(Double.isNaN( nst[0] ) && Double.isNaN( nst[1] )) || 
				!(isNonLinear || Double.isInfinite( nst[0] )); // <=> !A && !B
		
		boolean nst_notequal =
				(isNonLinear) && (!(nst_exists) || !( nst[0] == nst[1] )) ? true : false;
		
		System.out.println(( nst.length == 1 ) ? 
				"Die Nullstelle der linearen Gleichung ist: "+ 
					((nst_exists) ? nst[0] : "nicht vorhanden" ) : 
				"Die Nullstellen der quadratischen Gleichung sind: "+ 
					((nst_exists) ? ((nst_notequal) ? nst[0] +", "+ nst[1] : nst[0]) : "nicht vorhanden" ));
	}

	public static double[] nullstellen( double a, double b, double c ) {
		double p = 0;
		double q = 0;

		if ( a != 0 ) {
			p = b/a;
			q = c/a;
		}
		
		return (a == 0) ? 
				new double[]{ -c/b } : 
				new double[]{ -p/2 - Math.sqrt( p*p/4 -q ), -p/2 + Math.sqrt( p*p/4 -q )};
	}
}
                

Lösung von: Carsten Krahl (BA Leipzig)

#Lösung der Aufgabe mit GUI

import tkinter as tk
import math

def calc():
    if choose.get() == 1: #quadraitsich Funktion
        a = int(a_entry.get())
        b = int(b_entry.get())
        c = int(c_entry.get())
        try:     
            
            x1 = round((-b + math.sqrt(b**2-4*a*c))/(2*a),5)
            x2 = round((-b - math.sqrt(b**2-4*a*c))/(2*a),5)
            result =str("x1 = {0}\n x2 = {1}".format(x1, x2))
            erg.config(text = result)
        except:
            erg.config(text = "Keine Lösung\nÜberprüfen Sie Ihre Eingaben")

    else:
        a = int(a_entry.get())
        b = int(b_entry.get())
        if a == 0 and b == 0:
            erg.config(text = "Bei a = 0 und b = 0, gibt es unendlich viele Nullstellen")
            return
        elif a == 0 and b !=0:
            erg.config(text = "Steigung ist 0 ==> Keine Nullstelle")
        else:
            x1 = round(-b/a)
            result = str("x1 = {}".format(x1))
            erg.config(text = result)


def disable():
    if choose.get() == 0:
        c_entry.config(state = "disabled")
    else:
        c_entry.config(state = "normal")
    
main = tk.Tk()

choose = tk.IntVar()
choose.set(0)

choose_gleichung_linear = tk.Radiobutton(main, text = "Lineare Gleichung", variable = choose, value = 0, command = disable)
choose_gleichung_linear.grid()

choose_gleichung_quadrat = tk.Radiobutton(main, text = "Quadratische Gelichung", variable = choose, value = 1, command = disable)
choose_gleichung_quadrat.grid()


al = tk.LabelFrame(main, text = "a")
al.grid()
bl = tk.LabelFrame(main, text = "b")
bl.grid()
cl = tk.LabelFrame(main, text = "c")
cl.grid()

a_entry = tk.Entry(al)
a_entry.grid()
b_entry = tk.Entry(bl)
b_entry.grid()
c_entry = tk.Entry(cl, state = "disabled")
c_entry.grid()

but = tk.Button(main, text = "Rechne", command = calc)
but.grid()

erg = tk.Label(main, text = "")
erg.grid()

main.mainloop()

                

Lösung von: Py Thon ()

clc

gleichung = input("lineare(1) oder quadratische(2) Gleichung? ")

if gleichung == 1 then
    disp("f(x)=ax+b")
    a = input("a= ")
    b = input("b= ")
    x = -b/a
    disp("x = ")
    disp(x)
elseif gleichung == 2 then
    disp("f(x)=ax^2+bx+c")
    a = input("a= ")
    b = input("b= ")
    c = input("c= ")
    x1 = -b/2/a + sqrt(b^2/4/a^2 - c/a)
    x2 = -b/2/a - sqrt(b^2/4/a^2 - c/a)
    if x1 ~= x2 then
        disp("x1 = ")
        disp(x1)
        disp("x2 = ")
        disp(x2)
    else
        disp("x1 = ")
        disp(x1) 
    end
end

//Scilab
                

Lösung von: Name nicht veröffentlicht

function zeros(a, b, c) {
  if (!c) {
    // lineare gleichung
    if (a == 0 && b == 0) return Infinity;
    if (a == 0 && b != 0) return [];
    return -b / a;
  } else {
    // quadratische gleichung
    let x1 = (-b - Math.sqrt(b ** 2 - 4 * a * c)) / 2 * a,
        x2 = (-b + Math.sqrt(b ** 2 - 4 * a * c)) / 2 * a
    if (x1 == x2) return x1;
    else return [x1, x2];
  }
}
                

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

// NET 6.x | C# 6.x | VS-2022
IEnumerable<object> Zeros(params double[] p) {
    switch (p.Length) {
        case 2:  yield return (p[0], p[1]) switch { (0, 0) => "infinity", (0, _) => "nothing", (_, _) => -p[1] / p[0] }; break;
        case 3:  var x = (int i) => -p[1] + i * Math.Sqrt(p[1] * p[1] - 4 * p[0] * p[2]) / (2 * p[0]);
                 double x1 = x(-1), x2 = x(1);
                 yield return x1;
                 if (x1 != x2) yield return x2; break;
        default: yield return "nothing"; break;
    }
}
                

Lösung von: Jens Kelm (@JKooP)

// C++ 17
#include <iostream>
#include <string>
#include <optional>

std::string get_zeros(double a, double b, std::optional<double> c = std::nullopt) {
    if (c) {
        const auto x{ [&](auto i) {return (-b + i * sqrt(b * b - 4 * a * *c) / (2 * a)); } };
        const auto x1{ x(-1) }, x2{ x(1) };
        return (x1 == x2) ? std::to_string(x1) : std::to_string(x1) + ", " + std::to_string(x2);
    }
    if (!a) { return b ? "Nothing" : "Infinity"; }
    return std::to_string(-b / a);
}
                

Lösung von: Jens Kelm (@JKooP)

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 1
Schwierigkeit: Leicht
Webcode: 6abm-k4ys
Autor: ()

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen