Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Runden (2) (Anweisungen und Abfolgen)

Schreiben Sie eine Methode, die eine gebrochene Zahl (double) auf vier signifikante Ziffern rundet.

Beispiele:

Eingabe (real) Ausgabe (real)
0.777777777777… 0.7778
23.456789123… 23.46
0.00223322332233… 0.002233 (= 2.233 e -3)
12 372 889 12 370 000 (= 1.237 e 7)

0 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

4 Lösung(en)

wert = 7123.209;
wert.toPrecision(4);
                
Pseudocode der ECMA Spezifikation
Zitat: 

http://bclary.com/2004/09/26/ecma-262

15.7.4.7  Number.prototype.toPrecision(precision)

Return a string containing the number represented either in exponential notation with one digit before the significand's decimal point and precision- 1 digits after the significand's decimal point or in fixed notation with precision significant digits. If precision is undefined, call ToString (9.8.1) instead. Specifically, perform the following steps:

    1. Let x be this number value.

    2. If precision is undefined, return ToString(x).

    3. Let p be ToInteger(precision).

    4. If x is NaN, return the string "NaN".

    5. Let s be the empty string.

    6. If x >= 0, go to step 9.

    7. Let s be "-".

    8. Let x = -x.

    9. If x = +?, let m = "Infinity" and go to step 30.

    10. If p <1 or p > 21, throw a RangeError exception.

    11. If x != 0, go to step 15.

    12. Let m be the string consisting of p occurrences of the character '0'.

    13. Let e =0.

    14. Go to step 18.

    15. Let e and n be integers such that 10p- 1 <= n <10p and for which the exact mathematical value of n * 10e- p+ 1 - x is as close to zero as possible. If there are two such sets of e and n, pick the e and n for which n * 10e- p+ 1 is larger.

    16. Let m be the string consisting of the digits of the decimal representation of n (in order, with no leading zeroes).

    17. If e <-6 or e >= p, go to step 22.

    18. If e = p- 1, go to step 30.

    19. If e >= 0, let m be the concatenation of the first e+ 1 characters of m, the character '. ', and the remaining p-(e+ 1) characters of m and go to step 30.

    20. Let m be the concatenation of the string "0.",-( e+ 1) occurrences of the character '0', and the string m.

    21. Go to step 30.

    22. Let a be the first character of m, and let b be the remaining p- 1 characters of m.

    23. Let m be the concatenation of the three strings a, ".", and b.

    24. If e =0, let c = "+" and d = "0" and go to step 29.

    25. If e >0, let c = "+" and go to step 28.

    26. Let c = "-".

    27. Let e =- e.

    28. Let d be the string consisting of the digits of the decimal representation of e (in order, with no leading zeroes).

    29. Let m be the concatenation of the four strings m, "e", c, and d.

    30. Return the concatenation of the strings s and m.

    The length property of the toPrecision method is 1.

    If the toPrecision method is called with more than one argument, then the behaviour is undefined (see clause 15).

    An implementation is permitted to extend the behaviour of toPrecision for values of precision less than 1 or greater than 21. In this case toPrecision would not necessarily throw RangeError for such values.

                
/**
 * Zahlen auf "zählende Ziffern" (= signifikante Ziffern) runden.
 * 
 * @author Philipp Gressly (phi@gressly.ch)
 */
/*
 * History: first Implementation: Oct 11, 2010 Bugs :
 */
public class SignifikanteStellen {

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

    boolean mehrZiffern;

    void top() {
        System.out.println(signifikanteStellen(1.2, 4));
        System.out.println(signifikanteStellen(0.8, 4));
        System.out.println(signifikanteStellen(22345, 4));
        System.out.println(signifikanteStellen(-32345, 2));
        System.out.println(signifikanteStellen(0.004234, 2));
        System.out.println(signifikanteStellen(0.005234, 6));
        System.out.println(signifikanteStellen(0.000099994234, 2));
        System.out.println(signifikanteStellen(99.99, 2));
        System.out.println(signifikanteStellen(9.99, 2));
        System.out.println(signifikanteStellen(0, 3));
    }

    String signifikanteStellen(double orig, int prec) {
        if (0 == orig) {
            return nullenErzeugen(prec);
        }
        String vorzeichen = "";
        if (orig < 0.0) {
            orig = -orig;
            vorzeichen = "-";
        }
        // bewege die Zahl "orig" solange bis 1.0 <= orig < 10.0.
        // "shift" gibt an, um wie viele Stellen der
        // Dezimalpunkt dabei verschoben wurde.
        
        int shift = 0;
        double einstellig = orig;
        while (einstellig >= 10.0) {
            einstellig = einstellig / 10.0;
            shift = shift + 1;
        }
        while (einstellig < 1.0) {
            einstellig = einstellig * 10.0;
            shift = shift - 1;
        }
        // Rundungsfehler auf letzter Ziffer beheben.
        einstellig = einstellig + 2.0 * Math.ulp(einstellig);

        String ziffernfolge = makeZiffernfolge(einstellig, prec);
        String folgeGerundet = runden(ziffernfolge);

        if (mehrZiffern) {
            shift = shift + 1;
        }
        String result = verschiebeDezimalpunkt(folgeGerundet, shift);

        return vorzeichen + result;
    }

    /**
     * Verschiebe den Dezimalpunkt in der Ziffernfolge um "shift"
     */
    String verschiebeDezimalpunkt(String folgeGerundet, int shift) {
        if (0 > shift) {
            if (-1 == shift) {
                return "0." + folgeGerundet;
            }
            return "0." + nullenErzeugen(-shift - 1) + folgeGerundet;
        }
        // shift >= 0
        // if(0 == shift) {
        if (folgeGerundet.length() - 2 >= shift) {
            return folgeGerundet.substring(0, shift + 1) + "."
                    + folgeGerundet.substring(shift + 1);
        }
        if (folgeGerundet.length() - 1 == shift) {
            return folgeGerundet;
        }
        // add zeroes
        return folgeGerundet + nullenErzeugen(shift - folgeGerundet.length() + 1);
    }

    /**
     * Rundet auf (abhängig von der letzten Ziffer) Global: mehrZiffern, falls
     * beim Aufrunden mehr Ziffern entstehen, als ursprünglich vorhanden.
     * 
     * @param ziffernfolge
     * @return aufgerundete Ziffernfolge abhängig von der letzten Ziffer.
     */
    String runden(String ziffernfolge) {
        if (ziffernfolge.charAt(ziffernfolge.length() - 1) < '5') {
            return ziffernfolge.substring(0, ziffernfolge.length() - 1);
        }
        // aufrunden (da letzte Ziffer >= '5')
        ziffernfolge = ziffernfolge.substring(0, ziffernfolge.length() - 1);
        String result = "";
        int uebertrag = 1;
        int pos = ziffernfolge.length() - 1;
        while (pos >= 0) {
            char ziffer = ziffernfolge.charAt(pos);
            ziffer = (char) (ziffer + uebertrag);
            if (ziffer > '9') {
                ziffer = '0';
                uebertrag = 1;
            } else {
                uebertrag = 0;
            }
            pos = pos - 1;
            result = ziffer + result;

        }
        mehrZiffern = false;
        if (1 == uebertrag) {
            mehrZiffern = true;
            result = "1" + result;
        }
        return result;
    }

    /**
     * Erzeuge aus einem Double d (1.0 <= d < 10.0) eine Ziffernfolge mit "prec"
     * Stellen.
     */
    String makeZiffernfolge(double einstellig, int prec) {
        String result = "";
        while (prec + 1 > 0) {
            result = result + (int) einstellig;
            einstellig = einstellig % 1.0;
            einstellig = einstellig * 10;
            prec = prec - 1;
        }
        // System.out.println("Folge (+1): " + result);
        return result;
    }

    /**
     * Erzeuge String aus Nullen
     * 
     * @param prec
     *            z. B. 5
     * @return "00000"
     */
    String nullenErzeugen(int prec) {
        String result = "";
        while (prec > 0) {
            result = result + "0";
            prec--;
        }
        return result;
    }

} // end of class ToPrecision
                
package programmierenlernen.kapitel2;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Scanner;

public class Aufgabe_2_7 {

	public static void main(String[] args) {
		new Aufgabe_2_7().top();
	}
	
	void top() {
		double zahleingabe = eingabeDouble("Geben Sie eine Zahl ein:");
		
		BigDecimal bd = new BigDecimal(zahleingabe);
		bd = bd.round(new MathContext(4)); //Cannot invoke round(MathContext) on the primitive type double
		double zahlausgabe = bd.doubleValue(); //double bddouble = bd; -> Type mismatch. cannot convert from BigDecimal to double
		
		print("Gerundet auf vier(4) signifikante Stellen: " + zahlausgabe);
	}

	Scanner sc = new Scanner(System.in);
	double eingabeDouble(String eingabe) {
		print(eingabe);
		return sc.nextDouble();
	}
	
	void print(String textstring) {
		System.out.println(textstring);
	}
}
                

Lösung von: Jan Roth (Santis Training AG)

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 2
Schwierigkeit: k.A.
Webcode: z296-j92g
Autor: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen