+ 3
c++ convertion
char ch; int i =60; float f = 2.5; double dbl; ch = static_cast<char>(i); // int to char dbl = static_cast<double>(f); // float to double cout << dbl << endl; cout << f << endl; cout <<i << endl; cout << ch << endl; the char output ch each time we change i we get another char ... is the output ch secified or how it work.thank you
3 Antworten
+ 2
C++ internally treats characters as integers.
C++ also uses the ASCII character set.
in the ASCII character set, the letter "A" is represented by the number 65, B is represented by 66, C is represented by 67 and so on.
The tricky part of your code, was when you assigned an integer value "i" ,which is 60 , to the variable ch which is of type char.
Recall when I said C++ treats characters as integers.
when this assignment was made 👇
ch = i // ch = 60;
What happened was that C++ looked for the ASCII character represented by the value 60 (which in this case is the lesser than symbol "<"), and assigned that character to variable "ch".
so when you printed ch, you got the ASCII representation of 60, which is "<"
to understand better run this snippet and observe your results
for(int i = 65; i < 92; i++){
char ch = i;
std::cout<< ch << endl;
}
+ 13
• char
A char is a one byte value. Unlike other numeric types, it prints as a character, although it can be used in arithmetic expressions.
Character constants are enclosed in single quotes, as 'a'.
Most computers use ASCII conversion.
+ 12
The most important types are int, char, bool, double, and the containers string, vector, and map.
Summary of common types:
• int x; Fastest integer type (16-32 bits),
also short, long, unsigned
• char x; 8-bit character, '\0' to '\xFF'
or -128 to 127
• double x; 64 bit real + or - 1.8e308,
14 significant digits, also float
• bool x; true or false