Taschenrechner (Zeichenketten)
Schreiben Sie ein Programm, das einfache Berechnungen, die als
Zeichenketten (Strings) gegeben sind, durchführen kann. Die Eingabe besteht aus einer ersten positiven ganzen Zahl, gefolgt von einem Operator (+, -, * oder /) und einer zweiten positiven ganzen Zahl. Beispiele:
" 5 + 77"
"66 - 121"
"33 * 46"
"84 / 32"
0 Kommentare
10 Lösung(en)
/* REXX */
say "Bruno's Superrechner"
say "--------------------"
say " "
say "Eingabeformate:"
say "Zahl 1 / Operator / Zahl 2"
say "bzw. (nach dem ersten Ergebnis)"
say "Operator / Zahl 2"
say "Abbruch jederzeit mit 'e' moeglich."
say " "
/*-------------------*/
/* Rechnung einlesen */
/*-------------------*/
pull Zahl1 Oper Zahl2
/*------------*/
/* Rechnungen */
/*------------*/
do while Zahl1 <> 'E'
/*---------------*/
/* Neue Rechnung */
/*---------------*/
if Zahl2 <> '' then nop
/*-------------*/
/* Fortsetzung */
/*-------------*/
else do
Zahl2 = Oper
Oper = Zahl1
Zahl1 = Ergebnis
end
/*------------------*/
/* Korrekte Eingabe */
/*------------------*/
if verify(Zahl1,'0123456789.+-') == 0,
& verify(Zahl2,'0123456789.+-') == 0,
& (Oper == '+' | Oper == '-',
| Oper == ':' | Oper == '/' | Oper == 'X' | Oper =='*'),
then do
/*------------------------------------------*/
/* Rechnung ausführen und Ergebnis ausgeben */
/*------------------------------------------*/
select
when Oper == '+' then Ergebnis = Zahl1 + Zahl2
when Oper == '-' then Ergebnis = Zahl1 - Zahl2
when Oper == ':' | Oper == '/' then Ergebnis = Zahl1 / Zahl2
otherwise Ergebnis = Zahl1 * Zahl2
end
say Zahl1 Oper Zahl2 "=" Ergebnis
end /* Korrekte Eingabe */
/*---------------------*/
/* Fehlerhafte Eingabe */
/*---------------------*/
else
say "Eingabefehler, Eingabe korrigieren."
/*-------------------*/
/* Rechnung einlesen */
/*-------------------*/
pull Zahl1 Oper Zahl2
end /* Rechnungen */
/* Programmiersprache: PL/1 */
*process langlvl(saa2);
*process or('!');
*process prefix(nofofl);
*process limits(fixeddec(15,31));
(SUBSCRIPTRANGE, SIZE, STRINGRANGE, STRINGSIZE):
Rechner: proc() options(main);
/*----------*/
/* ON ERROR */
/*----------*/
on Error snap begin;
on Error SYSTEM;
display('Error <Enter>.') reply(theAnswer);
end;
/*----------*/
/* Builtins */
/*----------*/
dcl (length
,substr
,add
,subtract
,multiply
,divide
,round
,trim) builtin;
/*-----------*/
/* Variablen */
/*-----------*/
dcl theAnswer char(200) var;
dcl Zahl1_txt char(200) var;
dcl Zahl2_txt char(200) var;
dcl Oper_txt char(200) var;
dcl Zahl1_fixed dec fixed(31,13);
dcl Zahl2_fixed dec fixed(31,13);
dcl Ergebnis dec fixed(31,13);
dcl neue_Rechnung bit(1);
dcl UserInput_Status dec fixed(1);
/*--------------*/
/* Verarbeitung */
/*--------------*/
call display_UserIntro();
call get_UserInput();
Inputloop:
do while (Zahl1_txt ^= 'E'& Zahl1_txt ^= 'e');
UserInput_Status = UserInput_plausi();
if UserInput_Status = 0
then do;
call Ergebnis_berechnen();
call display_Resultat();
end;
else
call display_errorMsg(UserInput_Status);
call get_UserInput();
end Inputloop;
/*----------------*/
/* Unterprogramme */
/*----------------*/
/*--------------------*/
display_UserIntro: proc;
/*--------------------*/
display ("Bruno's Superrechner");
display ("--------------------");
display (" ");
display ("Eingabeformate:");
display ("Zahl 1 / Operator / Zahl 2");
display ("bzw. (nach dem ersten Ergebnis)");
display ("Operator / Zahl 2");
display ("Zahlen und Operator durch Leerschlag trennen!");
display ("Abbruch jederzeit mit 'e' moeglich.");
display (" ");
end display_UserIntro;
/*----------------*/
get_UserInput: proc;
/*----------------*/
dcl iLauf bin fixed(31);
dcl iStart bin fixed(31);
dcl iStopp bin fixed(31);
dcl txt(3) char(200) var;
dcl Help char(201) var;
display('Ihre Eingabe: ') reply(theAnswer);
txt(*) = '';
Help = trim(theAnswer)!!' ';
do iLauf = 1 to 3 while(length(Help) > 1);
iStart = verify(Help,' ');
iStopp = index(substr(Help,iStart),' ');
txt(iLauf)= substr(Help,iStart,(iStopp-iStart));
Help = trim(substr(Help,(iStopp+1)))!!' ';
end;
Zahl1_txt = txt(1);
Oper_txt = txt(2);
Zahl2_txt = txt(3);
/* Neue Rechnung */
if Zahl2_txt ^= ''
then
neue_Rechnung = '1'b;
/* Fortsetzung alte Rechnung */
else do;
neue_Rechnung = '0'b;
Zahl2_txt = Oper_txt;
Oper_txt = Zahl1_txt;
end;
end get_UserInput;
/*--------------------------------------*/
UserInput_plausi: proc returns(fixed(1));
/*--------------------------------------*/
dcl Help_df dec fixed(31,13);
if neue_Rechnung
& verify(Zahl1_txt,'0123456789.+-') ^= 0
then return(1);
if verify(Zahl2_txt,'0123456789.+-') ^= 0
then return(2);
if Oper_txt ^= '+'
& Oper_txt ^= '-'
& Oper_txt ^= ':' & Oper_txt ^= '/'
& Oper_txt ^= 'X' & Oper_txt ^= 'x' & Oper_txt ^='*'
then return(3);
Help_df = Zahl2_txt;
if Help_df = 0 & (Oper_txt = ':' ! Oper_txt = '/')
then return(4);
return(0);
end UserInput_plausi;
/*-------------------------*/
display_errorMsg: proc($Typ);
/*-------------------------*/
dcl $Typ dec fixed(1) parm;
select($Typ);
when(1) display("Zahl 1 falsch. Eingabe korrigieren.");
when(2) display("Zahl 2 falsch. Eingabe korrigieren.");
when(3) display("Operator falsch. Eingabe korrigieren.");
when(4) display("Teilung durch 0 nicht möglich.");
other display("Nicht näher definierter Fehler aufgetreten.");
end;
end display_errorMsg;
/*---------------------*/
Ergebnis_berechnen: proc;
/*---------------------*/
if neue_Rechnung
then do;
Zahl1_fixed = Zahl1_txt;
Zahl2_fixed = Zahl2_txt;
end;
else do;
Zahl1_fixed = Ergebnis;
Zahl2_fixed = Zahl2_txt;
end;
select;
when (Oper_txt = '+')
Ergebnis = add (Zahl1_fixed,Zahl2_fixed,31,13);
when (Oper_txt = '-')
Ergebnis = subtract(Zahl1_fixed,Zahl2_fixed,31,13);
when (Oper_txt = ':'
! Oper_txt = '/')
Ergebnis = divide (Zahl1_fixed,Zahl2_fixed,31,13);
otherwise
Ergebnis = multiply(Zahl1_fixed,Zahl2_fixed,31,13);
end;
end Ergebnis_berechnen;
/*-------------------*/
display_Resultat: proc;
/*-------------------*/
dcl Ergebnis_pic pic'-,---,---,---,---,---,--9V.9yyyyyyyyyyy';
dcl Ergebnis_char char(38) var;
Ergebnis_pic = round(Ergebnis,12);
Ergebnis_char = trim(Ergebnis_pic);
display("Ergebnis: "!!Ergebnis_char);
end display_Resultat;
end Rechner;
Lösung von: Bruno Keller (Santis Training AG)
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
# @autor Philipp Gressly Freimann
# 9. März 2011
#
# Aufgabe Taschenrechner
# Rechnung einlesen:
print "<Zahl> <Opreator> <Zahl>: "
zahl1,operator,zahl2=STDIN.gets.scan(/(\d+)\s*([\+\-\*\/])\s*(\d+)/).flatten
zahl1=zahl1.to_f
zahl2=zahl2.to_f
if('+' == operator)
puts zahl1 + zahl2
end
if('-' == operator)
puts zahl1 - zahl2
end
if('*' == operator)
puts zahl1 * zahl2
end
if('/' == operator)
puts zahl1 / zahl2
end
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
package ch.programmieraufgaben.strings;
import java.util.Scanner;
/**
* Programmieraufgabe 7.15 "Taschenrechner"
* @version 0.1 (Feb 5, 2015)
* @author Philipp Gressly Freimann
* (philipp.gressly@santis.ch)
*/
public class Taschenrechner {
public static void main(String[] args) {
try {
new Taschenrechner().top();
} catch (NumberFormatException nfe) {
// Warum diese 17? Das ist die Länge der englischen Java Fehlermeldung:
// "For input String:"
System.out.println("Fehler in der Zahl: " + nfe.getMessage().substring(17));
}
}
void top() {
float resultat = 0;
int operatorPosition; // position des Operators
char operator ; // Operatorzeichen
System.out.println("Rechnung eingeben:");
String rechnung = new Scanner(System.in).nextLine();
if(rechnung.indexOf("+") > 0) {
operatorPosition = rechnung.indexOf("+");
operator = '+';
} else if(rechnung.indexOf("*") > 0) {
operatorPosition = rechnung.indexOf("*");
operator = '*';
} else if(rechnung.indexOf("-") > 0) {
operatorPosition = rechnung.indexOf("-");
operator = '-';
} else if(rechnung.indexOf("/") > 0) {
operatorPosition = rechnung.indexOf("/");
operator = '/';
} else {
System.out.println("Fehler Operator + - * / nicht gefunden");
return;
}
String op1 = rechnung.substring(0, operatorPosition) .trim();
String op2 = rechnung.substring(operatorPosition + 1).trim();
float zahl1 = Float.parseFloat(op1);
float zahl2 = Float.parseFloat(op2);
if('+' == operator) {
resultat = zahl1 + zahl2;
} else if ('*' == operator) {
resultat = zahl1 * zahl2;
} else if ('-' == operator) {
resultat = zahl1 - zahl2;
} else if ('/' == operator) {
if(0 == zahl2) {
System.out.println("Divison durch 0!");
return;
}
resultat = zahl1 / zahl2;
}
System.out.println("Resultat: " + resultat);
}
} // end of class Taschenrechner
Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)
package ch.santis.programmierenlernen.kapitel7;
import java.util.Scanner;
public class Aufgabe_7_15 {
public static void main(String[] args) {
new Aufgabe_7_15().top();
}
// Aufgabe 7.15 Taschenrechner (ohne Fehlerbehandlung)
void top() {
String eingabe = eingabeString("Rechnung eingeben:\nBeispiel 5 + 77");
char operator = operatorsuchen(eingabe);
int zahl1 = erstezahlsuchen(eingabe, operator);
int zahl2 = zweitezahlsuchen(eingabe, operator);
double resultat = rechnung(zahl1, zahl2, operator);
System.out.println(zahl1 + " " + operator + " " + zahl2 + " = " + resultat);
}
public double rechnung(int zahl1, int zahl2, char operator) {
int resultat = 0;
if(operator == '+') {resultat = zahl1 + zahl2;}
else if(operator == '-') {resultat = zahl1 - zahl2;}
else if(operator == '*') {resultat = zahl1 * zahl2;}
else if(operator == '/') {
double resultat2 = (double)zahl1 / (double)zahl2;
return resultat2;
}
return resultat;
}
public char operatorsuchen(String eingabe) {
String ope = "";
if(eingabe.contains("+")) {ope = "+";}
else if(eingabe.contains("-")) {ope = "-";}
else if(eingabe.contains("*")) {ope = "*";}
else if(eingabe.contains("/")) {ope = "/";}
char operator = ope.charAt(0);
return operator;
}
public int erstezahlsuchen(String eingabe, char operator) {
int zahl = Integer.parseInt(eingabe.substring(0, eingabe.indexOf(operator)).trim());
return zahl;
}
public int zweitezahlsuchen(String eingabe, char operator) {
int zahl = Integer.parseInt(eingabe.substring(eingabe.indexOf(operator)+1).trim());
return zahl;
}
// String einlesen
Scanner sc = new Scanner(System.in);
public String eingabeString(String text) {
System.out.println(text);
return sc.nextLine(); //muss nextLine sein und nicht nur next
}
}
Lösung von: Jan Roth (Santis Training AG)
console.log(eval(prompt('Term:')));
Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)
// NET Core 3.x
using System;
using System.Text.RegularExpressions;
namespace CS_Aufgabe_Taschenrechner
{
class Program
{
static void Main(string[] args)
{
var m = "3 + 5";
var mc = new Regex(@"(\d+)\s*([\+\-\*\/]{1})\s*(\d+)").Match(m);
double.TryParse(mc.Groups[1].ToString(), out var a);
double.TryParse(mc.Groups[3].ToString(), out var b);
double result = mc.Groups[2].ToString() switch
{
"+" => a + b,
"-" => a - b,
"*" => a * b,
"/" => a / (b == 0 ? 1 : b),
_ => 0
};
Console.WriteLine($"{m} = {result}");
}
}
}
Lösung von: Jens Kelm (@JKooP)
// C++ 14 | VS-2022
#include <iostream>
#include <vector>
#include <algorithm>
struct Operation {
std::string command;
float (*ptr_func)(int a, int b);
};
float add_(int a, int b) { return a + b; }
float sub_(int a, int b) { return a - b; }
float mul_(int a, int b) { return a * b; }
float div_(int a, int b) { return a / (float)b; }
int main() {
std::string cmd;
int a, b;
const std::vector<Operation> op{ {"add", &add_}, {"sub", &sub_}, {"mul", &mul_}, {"div", &div_} };
std::cout << "Bitte Operation (add/sub/mul/div) waehlen: ";
std::cin >> cmd;
std::cout << "Bitte Werte (a b) leerzeichengtrennt eingeben: ";
std::cin >> a >> b;
const auto f{ find_if(op.begin(), op.end(), [&](Operation o) {return o.command == cmd; }) };
if(f != op.end())
std::cout << "Ergebnis: " << f->ptr_func(a, b) << "\n";
}
Lösung von: Jens Kelm (@JKooP)
// C++14 | VS-2022
#include<iostream>
#include<regex>
#include<vector>
static const auto evaluate(const std::string& term) {
const std::regex reg{ R"((\d+)\s*([\+\-\*\/]{1})\s*(\d+))" };
std::smatch match;
if (!std::regex_match(term, match, reg)) return 0.0;
const auto a{ static_cast<double>(std::stoi(match[1].str())) };
const auto b{ static_cast<double>(std::stoi(match[3].str())) };
switch (match[2].str()[0]) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / (b == 0 ? 1 : b);
default: return 0.0;
}
}
int main() {
std::vector<std::string>terms{ "2+2", "8- 5", "3 * 3", "10 /7" };
for (const auto& term : terms)
std::cout << term << " = " << evaluate(term) << "\n";
}
Lösung von: Jens Kelm (@JKooP)
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
int main(){
char buffer[20];
printf("Bitte Aufgabe (leerzeichengetrennt) eingeben: "); // 2 + 2
fgets(buffer, sizeof(buffer), stdin);
int c = 0;
char *val[3];
char cmp[] = "_ ";
char *tmp = strtok(buffer, cmp);
while(tmp != NULL && c < 3){
val[c++] = tmp;
tmp = strtok(NULL, cmp);
}
double a = atoi(val[0]);
double b = atoi(val[2]);
double res = 0;
switch(val[1][0]){
case '+': res = a + b; break;
case '-': res = a - b; break;
case '*': res = a * b; break;
case '/': res = a / b; break;
}
printf("%.2lf\n", res);
}
Lösung von: Jens Kelm (@JKooP)
Aktionen
Neue Lösung hinzufügen
Bewertung
Durchschnittliche Bewertung:
Meta
Zeit: | 2 |
Schwierigkeit: | k.A. |
Webcode: | 6nmz-eiot |
Autor: | Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch) |