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.

int zu float ... hmm

Empfohlene Antworten

Veröffentlicht

Hi zusammen,

erstmal hier der Code.


int a=10,b=3;

float c=0;


c = a*1./b;

cout << c;

Es geht um die Problematik dass wenn ich 2 Integer durcheinander teile und das Ergebniss dann in ein Float speichere. Naja ich frag mich grad warum man das in C++ so blöd machen muss? Wieso geht nicht einfach:

c = a/b;

Deshalb deklariere ich ja c als float das der das Ergebniss ( die Zuweisung) als Kommastelle versteht.

Kann mir das mal jemand erklären, denn bis jetzt hab ichs halt so hingenommen, dass des C++ einfach net blickt ...

cu

alligator

Hoi,

zu 1. Aehmmm wo ist denn da nun ein Problem?

zu 2. Wieso findest das komisch?

ein c = (float a) / b; waere ja sowas wie eine versuchte neu Deklaration von a als float, was man aber so nicht darf.

und ein c = (float)a/b; ...nuja dabei ist das (float) ja nur ein Casting, waere also so aehnlich, also wenn du gleich ein float a = 10; festgelegt haettest....da das dann keine reine Integer Divison mehr ist wird das Ergebnis auch nicht mehr auf ein Int gekuerzt.

CU

Goos

Der Grund, warum dies

int a=10,b=3;

float c;


c=a/b;

nicht funktioniert ist, daß der Compiler erst den Ausdruck a/b ausrechnet (Ergebnis ist vom Typ int) und dann den Wert c zuweist (int wird in float umgewandelt).

Sorgt man aber dafür, daß eine der beiden Variablen, also a oder b, vorher in float umgewandelt wird, dann ist auch das Ergebnis der Division vom Typ float, denn C wandelt bei verschiedenen Typen bei einer Operation immer erst eine der beiden Variablen so um, daß beide den gleichen Typ haben, führt dann die Operation aus, deren Ergebnis dann vom gleichen Typ ist.

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.