Geldbetrag (Felder)
Geben Sie von einem Geldbetrag (in Euro und Cent) die nötigen Noten und Münzen
aus. In Euro existieren die folgenden Beträge:
- Münzen (in Cent): 1, 2, 5, 10, 20, 50
- Münzen und Noten (in Euro): 1, 2, 5, 10, 20, 50, 100, 200, 500
Beispiele:
betraege(53.26)
-> 50.00, 2.00, 1.00, 0.20, 0.05, 0.01
betraege(99.95)
-> 50.00, 20.00, 20.00, 5.00, 2.00, 2.00, 0.50, 0.20, 0.20, 0.05
Bemerkung zu Rundungsfehlern: Vergleichen Sie gebrochene Zahlen (double) nicht auf Gleichheit "=" (bzw. ? und ?). Anstelle von if(x = y) schreiben Sie für eine vorgegebene Rechengenauigkeit (z. B. eps := 0.0001)
if(abs(x - y) < eps).
0 Kommentare
14 Lösung(en)
import java.util.Scanner;
class Geldbetraege {
public static void main(String[] args) {
new Geldbetraege().top(); }
double EPS = 0.0001; // Rechengenauigkeit
double[] EINHEITEN = {
500.00, 200.00, 100.00,
50.00, 20.00, 10.00,
5.00, 2.00, 1.00,
0.50, 0.20, 0.10,
0.05, 0.02, 0.01 };
void top() {
double betrag = einlesen("Betrag");
int[] anzahlen = anzahlenRechnen(betrag);
ausgabe(anzahlen); }
double einlesen(String meldung) {
Scanner sc = new Scanner(System.in);
System.out.println(meldung + ": ");
return sc.nextDouble(); }
int[] anzahlenRechnen(double betrag) {
int[] anzahlen = new int[EINHEITEN.length];
for(int i = 0; i < EINHEITEN.length; i++) {
betrag = reduziere(betrag, i, anzahlen);
}
return anzahlen; }
/**
* Vermindere den Betrag und zähle die Anzahl der
* nötigen Werte im "anzahlen"-array dazu
* @param i index in den beiden arrays
* @return restbetrag
*/
double reduziere(double betrag, int i, int[] anzahlen) {
double actWert = EINHEITEN[i];
// EPS: Rechengenauigkeit
while(betrag + EPS > actWert) {
betrag = betrag - actWert;
anzahlen[i] ++;
}
return betrag; }
void ausgabe(int[] anzahlen) {
for(int i = 0; i < EINHEITEN.length; i++) {
bedingteAusgabe(anzahlen[i], i);
}
}
/**
* Einheiten nur ausgeben, wenn diese auch wirklich vorkommen.
*/
void bedingteAusgabe(int anzahl, int index) {
if(anzahl > 0) {
System.out.print(anzahl + " x EURO " );
formattierteBetragsausgabe(EINHEITEN[index]);
System.out.println(); // nächste Zeile
}
}
/**
* Ausgabe mit immer 2 Nachkommastellen.
*/
void formattierteBetragsausgabe(double d) {
System.out.printf("%6.2f", d); }
} // end of class Geldbetraege
package com.cs.santis.geldbetrag;
import com.cs.santis.input_helper;
/*
* @author Mike Wong
*
* @date 19.01.2011
*/
public class Main {
double betrag;
double schritt;
public static void main(String[] args) {
new Main().top();
}
void top() {
betrag = input_helper.readDouble("Wechselbetrag ");
berechnen(betrag);
}
void berechnen(Double d) {
int betrag = (int) (d * 100);
double schritte[] = {50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1};
int idx = 0;
int cnt = 0;
while (idx<schritte.length) {
if (betrag>=schritte[idx]) {
cnt++;
betrag-=schritte[idx];
if (betrag<schritte[idx]) {
System.out.println(cnt + "x " + (schritte[idx++]/100) + " Euro");
cnt=0;
}
} else {
idx++;
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////
package com.cs.santis;
import java.util.Scanner;
public class input_helper {
private static Scanner sc = new Scanner(System.in);
public static int readInt(String message) {
System.out.println(message + " eingeben:");
return sc.nextInt();
}
public static double readDouble(String message) {
System.out.println(message + " eingeben:");
return sc.nextDouble();
}
public static String readString(String message) {
System.out.println(message + " eingeben:");
return sc.next();
}
public static String readLine(String message) {
System.out.println(message + " eingeben:");
return sc.nextLine();
}
}
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
package com.cs.santis.geldbetrag;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class Model {
ActionListener listener;
double schritt;
ArrayList<String> ergebnisse = new ArrayList<String>();
void addListener(ActionListener al) {
this.listener = al;
}
void setBetrag(Double d) {
berechnen(d);
fireEvent();
}
private void fireEvent() {
listener.actionPerformed(null);
}
ArrayList<String> getErgebnisse() {
return ergebnisse;
}
void berechnen(Double d) {
int betrag = (int) (d * 100);
double schritte[] = {50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1};
int idx = 0;
int cnt = 0;
while (idx<schritte.length) {
if (betrag>=schritte[idx]) {
cnt++;
betrag-=schritte[idx];
if (betrag<schritte[idx]) {
ergebnisse.add(cnt + "x " + (schritte[idx++]/100) + " Euro");
cnt=0;
}
} else {
idx++;
}
}
}
}
//////////////////////////////////////////////////////////
package com.cs.santis.geldbetrag;
import javax.swing.*;
/*
* Berechnet die grösstmöglichen Noten/Münzen für den eingegebenen Euro-Betrag aus
* Lösung mit GUI (Eingabefeld, Button und Ausgabelabel)
* @author Mike Wong
*
* @date 19.01.2011
*/
public class GUI {
JFrame jf = new JFrame("Geldbetrag");
JTextField jt = new JTextField();
SimpleLabelView jl = new SimpleLabelView();
JButton jb = new JButton("Absenden");
Model myModel = new Model();
MyListener ml = new MyListener(myModel);
public static void main(String[] args) {
new GUI().top();
}
void top() {
createLayout();
myModel.addListener(jl);
ml.addTextField(jt);
}
private void createLayout() {
JPanel mainPanel = makeMainPanel();
jl.setModel(myModel);
jb.addActionListener(ml);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setContentPane(mainPanel);
jf.pack();
jf.setVisible(true);
}
private JPanel makeMainPanel() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(jt);
mainPanel.add(jb);
mainPanel.add(jl);
return mainPanel;
}
}
//////////////////////////////////////////////////////////////
package com.cs.santis.geldbetrag;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class MyListener implements ActionListener {
JButton jb;
JLabel jl;
JTextField jt;
Model myModel;
public MyListener(Model m) {
this.myModel = m;
}
@Override
public void actionPerformed(ActionEvent arg0) {
myModel.setBetrag(Double.parseDouble(jt.getText()));
}
public void addTextField(JTextField jt) {
this.jt = jt;
}
}
////////////////////////////////////////////////////////////////////////
package com.cs.santis.geldbetrag;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JLabel;
public class SimpleLabelView extends JLabel implements ActionListener {
private Model myModel;
public SimpleLabelView() {
this.setText(" ");
}
void setModel(Model m) {
this.myModel = m;
}
@Override
public void actionPerformed(ActionEvent ae) {
ArrayList<String> ergebnisse = myModel.getErgebnisse();
String out = "";
for (int i=0;i<ergebnisse.size()-1;i++) {
out += ergebnisse.get(i) + ", ";
}
out += ergebnisse.get(ergebnisse.size()-1);
this.setText(out);
}
}
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/* ----------------------------------------
*
* Copyright Elias Rüedi
* 2013
*
* ----------------------------------------*/
namespace Aufgabe_6._13_Geldbetrag
{
class Program
{
static void Main(string[] args)
{
string ausgabe = "500.00";
bool start = true;
Console.Write("Betrag eingeben ...");
Console.WriteLine();
double betrag = Convert.ToDouble(Console.ReadLine());
while (betrag > 0)
{
if (betrag / Convert.ToDouble(ausgabe) >= 1 && start)
{
Console.Write("-> ");
Console.Write(Convert.ToString(ausgabe));
betrag -= Convert.ToDouble(ausgabe);
start = false;
}
if (betrag / Convert.ToDouble(ausgabe) >= 1)
{
Console.Write(", " + Convert.ToString(ausgabe));
betrag -= Convert.ToDouble(ausgabe);
}
else
{
switch (ausgabe)
{
case "500.00": ausgabe = "200.00"; break;
case "200.00": ausgabe = "100.00"; break;
case "100.00": ausgabe = "50.00"; break;
case "50.00": ausgabe = "20.00"; break;
case "20.00": ausgabe = "10.00"; break;
case "10.00": ausgabe = "5.00"; break;
case "5.00": ausgabe = "2.00"; break;
case "2.00": ausgabe = "1.00"; break;
case "1.00": ausgabe = "0.50"; break;
case "0.50": ausgabe = "0.20"; break;
case "0.20": ausgabe = "0.10"; break;
case "0.10": ausgabe = "0.05"; break;
case "0.05": ausgabe = "0.02"; break;
case "0.02": ausgabe = "0.01"; break;
}
}
}
}
}
}
Lösung von: Elias Rüedi (KFTG)
{$R+}
{$B+}
{FernUni}
program GeldBetrag (input,output);
{Eingabe von Geld und Ausgabe - Aufteilung des Betrages in kleinen Mengen}
const
GRENZE = 15;
type
tIndex = 1..GRENZE;
tFeld = array[tIndex] of real;
var
Eingabe : real;
procedure MuenzeKnotenVerteilung ( inEingabe : real );
{Eingabe Geldbetrag ausgabe Meunzen und Notenverteilung}
var
eps,
Ergebnis,
Vergleicher,
Zws : real;
Feld : tFeld;
LaufIndex : integer;
begin
LaufIndex := 1;
Feld[1] := 500.00;
Feld[2] := 200.00;
Feld[3] := 100.00;
Feld[4] := 50.00;
Feld[5] := 20.00;
Feld[6] := 10.00;
Feld[7] := 5.00;
Feld[8] := 2.00;
Feld[9] := 1.00;
Feld[10] := 0.50;
Feld[11] := 0.20;
Feld[12] := 0.10;
Feld[13] := 0.05;
Feld[14] := 0.02;
Feld[15] := 0.01;
eps := 0.0001;
Vergleicher := 1;
Ergebnis := inEingabe;
Zws := 0;
write('-> ');
while (Ergebnis > 0) and (LaufIndex <= 15) do
begin
Zws := Ergebnis / Feld[LaufIndex];
if ( Zws > Vergleicher) then
{Vermindere den Betrag in Münzen wenn eine Verteilung möglich}
begin
Ergebnis := (Ergebnis + eps) - Feld[LaufIndex];
write(Feld[LaufIndex]:2:2,', ');
LaufIndex := 1;
end
else
begin
LaufIndex := LaufIndex + 1;
end
end; {while ende}
end; {MuenzeKnotenVerteilung Ende}
begin
write('Geben Sie ein Betrag ein: ');
readln(Eingabe);
MuenzeKnotenVerteilung(Eingabe);
readln(); {Ausgabe auf der Konsole zu sehen}
end.
Lösung von: Name nicht veröffentlicht
program Geldbetrag(input,output);
{ Lösung in Standardpascal, daher ist die Feldinitialisierung etwas umständlich }
type
tIndex = 1..15;
tWerte = array [tIndex] of Real;
var
Werte: tWerte;
i : tIndex;
Betrag: real;
istAnfang: Boolean;
procedure initialisiereWerte(var ioWerte: tWerte);
begin
ioWerte[1] := 500.00;
ioWerte[2] := 200.00;
ioWerte[3] := 100.00;
ioWerte[4] := 50.00;
ioWerte[5] := 20.00;
ioWerte[6] := 10.00;
ioWerte[7] := 5.00;
ioWerte[8] := 2.00;
ioWerte[9] := 1.00;
ioWerte[10] := 0.50;
ioWerte[11] := 0.20;
ioWerte[12] := 0.10;
ioWerte[13] := 0.05;
ioWerte[14] := 0.02;
ioWerte[15] := 0.01;
end;
procedure PfeilOderKomma(var ioIstAnfang:Boolean);
{ Pfeil oder Komma ausgeben }
begin
if istAnfang then
begin
write('-> ');
istAnfang := false;
end
else
write(', ');
end;
procedure GeldAusgeben(
var ioBetrag:real;
inWert:real;
var ioIstAnfang:Boolean);
{ Wert ausgeben, wenn Betrag ihn deckt, und Betrag verringern }
begin
while inWert <= ioBetrag do
begin
PfeilOderKomma(ioIstAnfang);
write(inWert:2:2);
ioBetrag := ioBetrag - inWert;
end;
end;
{ Hauptprogramm }
begin
istAnfang := true;
initialisiereWerte(Werte);
readln(Betrag);
Betrag := Betrag + 0.002; { Rundungsfehler ausgleichen }
for i:= 1 to 15 do
GeldAusgeben(Betrag, Werte[i], istAnfang);
writeln();
end.
Lösung von: Michael Mendelsohn ()
#Geldbetrag
euro_liste = [500, 200, 100, 50, 20, 10, 5, 2, 1]
cent_liste = [50, 20, 10, 5, 2, 1]
e_liste = []
c_liste = []
betrag = float(input('Betrag eingeben: ')) #betrag = 99.95
cent = int(betrag * 100 % 100)
euro = int(betrag - cent/100)
def ausgabe(b, liste, a_liste):
ec = 0
while ec < len(liste):
if liste[ec] <= b :
b = b - liste[ec]
a_liste.append(liste[ec])
if b < liste[ec]:
ec +=1
if b > 0:
ausgabe(b)
ausgabe(euro, euro_liste, e_liste)
ausgabe(cent, cent_liste, c_liste)
print('\nEuro', e_liste, ' Cent', c_liste)
print('\nSumme Euro + Cent: ', sum(e_liste) + sum(c_liste)/100, '€')
Lösung von: Alex Groeg (Freies Lernen)
function cashOut(amount, toStr) {
toStr = toStr || false;
amount = parseInt(amount * 100);
let bulks = [5e4, 2e4, 1e4, 5e3, 2e3, 1e3, 500, 200, 100, 50, 20, 10, 5, 2, 1],
out = []; i = 0;
while (amount > 0) {
while (amount >= bulks[i]) {
amount -= bulks[i];
out.push(bulks[i] / 100);
}
i++;
}
if (!toStr) return out;
/*-------------------------------*\
| selbst auferlegte zusatzaufgabe |
\*-------------------------------*/
else {
let str = [];
str.push([out.shift(), 1]);
while (out.length > 0) {
let x = out.shift();
if (str[str.length-1][0] == x) str[str.length-1][1]++;
else str.push([x, 1]);
}
for (i = 0; i < str.length; i++)
if (str[i][0] < 1) {
str[i].push('¢');
str[i][0] = str[i][0] * 100;
} else str[i].push('€');
for (i = 0; i < str.length; i++)
str[i] = `${str[i][1]} × ${str[i][0]}${str[i][2]}`;
return str.join(', ');
}
}
// ausgabe
console.log(cashOut(53.26));
console.log(cashOut(53.26, true));
console.log(cashOut(199.95));
console.log(cashOut(199.95, true));
console.log(cashOut(1000000.99));
console.log(cashOut(1000000.99, true)); // lissalanda@gmx.at
Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)
// NET 6.x | C# 10.x | VS-2022
CashOut(1026.76).ToList().ForEach(x => Console.WriteLine(x));
List<(string note, int count)> CashOut(double amount)
{
var amountInt = (int)(amount * 100);
var lstCurrency = new List<(string note, int value)> { ("500 Euro", 50_000), ("200 Euro", 20_000),
("100 Euro", 10_000), ("50 Euro", 5_000), ("20 Euro", 2_000), ("10 Euro", 1_000),
("5 Euro", 500), ("2 Euro", 200), ("1 Euro", 100), ("50 Cent", 50), ("20 Cent", 20),
("10 Cent", 10), ("5 Cent", 5), ("2 Cent", 2), ("1 Cent", 1) };
var lstOut = new List<(string note, int count)>();
for (int i = 0; i < lstCurrency.Count; i++)
{
var intVal = amountInt / lstCurrency[i].value;
if (intVal >= 1) lstOut.Add((lstCurrency[i].note, intVal));
amountInt %= lstCurrency[i].value;
if (amountInt == 0) break;
}
return lstOut;
}
Lösung von: Jens Kelm (@JKooP)
// C++ 17
#include <iostream>
#include <vector>
#include <tuple>
std::vector<std::tuple<std::string, int>> cash_out(double amount) {
auto amount_int{ (int)(amount * 100) };
std::vector<std::tuple<std::string, int>> lst_currency { {"500 Euro", 50'000}, {"200 Euro", 20'000},
{"100 Euro", 10'000}, {"50 Euro", 5'000}, {"20 Euro", 2'000}, {"10 Euro", 1'000},
{"5 Euro", 500}, {"2 Euro", 200}, {"1 Euro", 100}, {"50 Cent", 50}, {"20 Cent", 20},
{"10 Cent", 10}, {"5 Cent", 5}, {"2 Cent", 2}, {"1 Cent", 1} };
std::vector<std::tuple<std::string, int>> lst_out;
for (const auto& c : lst_currency) {
auto value_int{ amount_int / std::get<1>(c) };
if (value_int >= 1)lst_out.push_back({ std::get<0>(c), value_int });
amount_int %= std::get<1>(c);
if (amount_int == 0) break;
}
return lst_out;
}
int main() {
auto co{ cash_out(1026.76) };
for(const auto& i : co)
std::cout << std::get<1>(i) << " x " << std::get<0>(i) << std::endl;
}
Lösung von: Jens Kelm (@JKooP)
// C++ 20 | VS- 2022
#include <iostream>
#include <vector>
using uint = unsigned;
struct currency {
uint value, number;
};
std::vector<double> cur{ 5e4, 2e4, 1e4, 5e3, 2e3, 1e3, 500, 200, 100, 50, 20, 10, 5, 2, 1 };
inline const auto cash_out(double amount) {
auto cents{ uint(amount * 100) };
std::vector<currency> out{};
for (const auto value : cur) {
const auto tmp{ cents / value };
if (tmp >= 1) out.push_back(currency(value, tmp)); // C++ 20!
cents %= uint(value);
if (!cents) break;
}
return out;
}
inline auto operator<<(std::ostream& os, currency cu) -> std::ostream& {
os << cu.number << " x ";
if (cu.value > 99) os << cu.value / 100 << " Euro";
else os << cu.value << " Cent";
return os;
}
constexpr auto print{ [] <typename T>(T t) { for (const auto& c : t) std::cout << c << "\n"; } }; // c++ 20!
auto main() -> int{
const auto co{ cash_out(1026.76) };
print(co);
}
Lösung von: Jens Kelm (@JKooP)
/*
C++ 20 | VS - 2022
std:c++20 MSVC only!
*/
#include <iostream>
#include <vector>
#include <array>
#include <format>
struct currency {
size_t value, number;
};
const std::array<size_t, 15> cur_arr{
50'000, 20'000, 10'000, 5'000, 2'000, 1'000,
500, 200, 100, 50, 20, 10, 5, 2, 1 };
inline static const auto cash_out(const auto&& amount_) {
auto cents{ size_t(amount_ * 100) };
std::vector<currency> out{};
for (const auto& val : cur_arr) {
const auto tmp{ cents / val };
if (tmp >= 1) out.push_back(currency(val, tmp));
cents %= val;
if (!cents) break;
}
return out;
}
inline static auto operator<<(std::ostream& os_, const currency& cu_) noexcept -> std::ostream& {
os_ << std::format("{:2} x ", cu_.number);
if (cu_.value > 99) os_ << std::format("{:3} Euro",cu_.value / 100);
else os_ << std::format("{:3} Cent",cu_.value);
return os_;
}
constexpr auto print{ [] (auto&& con_) { for (const auto& elem : con_) std::cout << elem << "\n"; } };
auto main() -> int {
const auto co{ cash_out(1026.76) };
print(co);
}
/*
Ausgabe:
2 x 500 Euro
1 x 20 Euro
1 x 5 Euro
1 x 1 Euro
1 x 50 Cent
1 x 20 Cent
1 x 5 Cent
1 x 1 Cent
*/
Lösung von: Jens Kelm (@JKooP)
' VBA
' (1) Klassenmodule (als Datentyp)
' Currency_t
Public cur_val As Long
Public cur_num As Long
' (2) Module
' Cash
Public Function CashOut(ByVal amount As Double)
Dim out() As Currency_t
Dim cur_t As Currency_t
Dim val As Variant
Dim cur_arr As Variant
Dim i As Integer
Dim cents As Long
Dim tmp As Long
cur_arr = Array(50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1)
cents = amount * 100
For Each val In cur_arr
tmp = cents \ val
If tmp >= 1 Then
ReDim Preserve out(i)
Set cur_t = New Currency_t
cur_t.cur_val = val
cur_t.cur_num = tmp
Set out(i) = cur_t
i = i + 1
cents = cents Mod val
If cents = 0 Then Exit For
End If
Next val
CashOut = out
End Function
Public Function ToString(ByVal cur_t As Currency_t)
Dim str As String
str = Right(" " & cur_t.cur_num, 2) & " x "
If cur_t.cur_val > 99 Then
str = str & Right(" " & cur_t.cur_val / 100, 3) & " Euro"
Else
str = str & Right(" " & cur_t.cur_val, 3) & " Cent"
End If
ToString = str
End Function
Sub PrintArr(ByVal cur_arr As Variant)
Dim elem As Variant
For Each elem In cur_arr
Debug.Print ToString(elem)
Next elem
End Sub
Sub Main()
PrintArr CashOut(1026.76)
End Sub
' Ausgabe
' 2 x 500 Euro
' 1 x 20 Euro
' 1 x 5 Euro
' 1 x 1 Euro
' 1 x 50 Cent
' 1 x 20 Cent
' 1 x 5 Cent
' 1 x 1 Cent
Lösung von: Jens Kelm (@JKooP)
#include <stdio.h>
const size_t cur_arr[15] = {
50000, 20000, 10000, 5000, 2000, 1000,
500, 200, 100, 50, 20, 10, 5, 2, 1 };
void cash_out(double amount) {
size_t cents = (size_t)(amount * 100);
for(size_t i = 0; i < 15; i++){
size_t tmp = (cents / cur_arr[i]);
if(tmp >= 1){
printf("%2i x ", tmp);
if(cur_arr[i] > 99) printf("%3i Euro\n", cur_arr[i] / 100);
else printf("%3i Cent\n", cur_arr[i]);
}
cents %= cur_arr[i];
if(!cents) break;
}
}
int main(){
cash_out(1026.76);
}
Lösung von: Jens Kelm (@JKooP)
Aktionen
Neue Lösung hinzufügen
Bewertung
Durchschnittliche Bewertung:
Meta
Zeit: | 1 |
Schwierigkeit: | k.A. |
Webcode: | 6juh-7y3z |
Autor: | Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch) |