Zum Inhalt springen
View in the app

A better way to browse. Learn more.

Fachinformatiker.de

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Eine Formel ausrechnen

Empfohlene Antworten

Veröffentlicht

Hallo Leute,

ich habe folgendes Problem, ich habe einen String mit einer Formel:

a=10+5*10*5

In die Variable a soll das Ergebnis hinter dem gleichheitszeichen eingetragen werden. In diesem Fall also 260. Das Speichen in die Variable klappt soweit, nur das Rechnen leider nicht. Ich schneide immer einen Teil aus dem String aus, errechne diesen und schreibe ihn mit der Replace Funktion zurück, dabei wird leider nicht immer sauber ersetzt.

Hier ist der Code zum errechnen:


double calculate(string strEingabe)

{

	// Überprüfung nach Klammern -> REKURSION

	int iPos = strEingabe.find_first_of('(');


	if (iPos != -1)

	{

		int iNext = strEingabe.rfind(')');

		strEingabe.replace(iPos, iNext-iPos, doubleToString(calculate(strEingabe.substr(iPos+1, iNext-iPos-1))));

	}


	// Berechnen der Eingabe.

	double dNumber=0, dFirstNumber=0, dLastNumber=0, dResult=0;;

	char cCalculator[4] = {'*', '/', '+', '-'};


	for (int i=0; i < sizeof(cCalculator) / sizeof(cCalculator[0]); ++i)

	{

		iPos = strEingabe.find_first_of(cCalculator[i]);


		while (iPos != -1)

		{

			// Wir müssen nach den jeweiligen Operatoren suchen.

			int iLeft=0, iRight=0;


			for (int j=iPos-1; j >= 0; --j)

			{

				iLeft = j;


				if (IsOperator(strEingabe[j]))

					break;

			}


			for (int j=iPos+1; j <= strEingabe.length(); ++j)

			{

				iRight = j;


				if (IsOperator(strEingabe[j]))

					break;

			}


			// Wir holen uns den String zum berechnen und setzen diesen wieder in den restlichen String ein.

			dResult = calculator(atof(strEingabe.substr(iLeft, iPos).data()), atof(strEingabe.substr(iPos+1, iRight).data()), cCalculator[i]);

			strEingabe.replace(iLeft, iLeft+iRight, doubleToString(dResult));


			// Nächste Position für den Start bestimmen.

			iPos = strEingabe.find_first_of(cCalculator[i], iPos+1);

		}

	}


	return atof(strEingabe.data());

}

Wo liegt der Fehler, über eine Hilfe würde ich mich freuen.

Beste Grüße und gutes neues

Patrick

Archiv

Dieses Thema wurde archiviert und kann nicht mehr beantwortet werden.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.