C++ Numerische Typen: Praktischer Leitfaden
Bei Zahlen nutzen wir primitive Datentypen: int, short, long, float, double etc. Wertebereiche wurden bei Datentypen bereits behandelt.
Zahlen definieren in C++
Konsolidiertes Beispiel:
#include <iostream>
using namespace std;
int main() {
short s; int i; long l; float f; double d;
s = 10; i = 1000; l = 1000000; f = 230.47; d = 30949.374;
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
Ausgabe:
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
Mathematische Operationen in C++
C++ bietet eingebaute mathematische Funktionen (Standard C/C++ Bibliotheken). Header <cmath> einbinden.
| Nr. | Funktion & Zweck |
|---|---|
| 1 | double cos(double) – Kosinus (Winkel in Radiant) |
| 2 | double sin(double) – Sinus |
| 3 | double tan(double) – Tangens |
| 4 | double log(double) – Natürlicher Logarithmus |
| 5 | double pow(double, double) – Potenz (Basis, Exponent) |
| 6 | double hypot(double, double) – Hypotenuse (Katheten) |
| 7 | double sqrt(double) – Quadratwurzel |
| 8 | int abs(int) – Absolutwert (Integer) |
| 9 | double fabs(double) – Absolutwert (Float) |
| 10 | double floor(double) – Abrunden (größte ganze Zahl ≤ Argument) |
Beispiel
#include <iostream>
#include <cmath>
using namespace std;
int main() {
short s = 10; int i = -1000; long l = 100000;
float f = 230.47; double d = 200.374;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow(d, 2) :" << pow(d, 2) << endl;
return 0;
}
Ausgabe:
sin(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow(d, 2) :40149.7
Zufallszahlen in C++
Zwei Funktionen: rand() (pseudo-zufällig) und srand() (Seed setzen).
Beispiel mit time() als Seed:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
int i, j;
srand((unsigned)time(NULL)); // Seed
for(i = 0; i < 10; i++) {
j = rand();
cout << " Random Number : " << j << endl;
}
return 0;
}
Beispielausgabe (variiert):
Random Number : 1748144778
Random Number : 630873888
Random Number : 2134540646
...
C Sprache
- C++-Operatoren meistern: Ein vollständiger Leitfaden mit praktischen Beispielen
- C++-Kommentare: Best Practices für lesbaren, wartbaren Code
- C++ Klassentemplates meistern: Ein praktischer Leitfaden
- C++ Variablen und Datentypen: Experten‑Guide zu int, double, char, string, bool
- C++ Programmiersprache: Überblick & Kernfeatures
- C++ Konstanten & Literale: Typen, Syntax & Best Practices
- C++ Operatoren: Typen, Nutzung & Best Practices
- C++ Numerische Typen: Praktischer Leitfaden
- C++ Referenzen: Konzepte & Unterschiede zu Pointern
- C++ Templates: Generische Programmierung meistern