I try to get in the response the variable t2 not as an int type, but as a float . Those. Now when I enter the number 457 , I have number two = 5 , and I want to get 5.7 . The code is already with an example, as I try to do, but it still outputs without tenths. What am I doing wrong?

 int e, n; float s, t2; cout << "vvedite n\n"; cin >> n; s = float(n) / 100 ; // первая цифра t2 = float ((n / 10) % 10); // вторая цифра e = n % 10; // третья цифра cout << "number one = " << float(s) << endl; cout << "number two = " << float(t2) << endl; cout << "number fri = " << e << endl; 

    2 answers 2

    From a whole number, you never get by casting a real with a non-zero fractional part. She just nowhere to take it. If you want to get the tail without the high order, then the simplest option is to simply subtract the whole part associated with the high order before dividing:

     int n = 457; s = n / 100.0; // 4.57 t2 = (n - static_cast<int>(s) * 100) / 10.0; // 5.7 e = n % 10; // 7 

    If desired, you can wrap in a cycle to work not only with three-digit numbers.

      You have a variable t2 and so is a type of float. The modular operation (%) is not used with floating point types. Exit - use the fmod function from the standard library. In addition, to get 5.7 you need to take it a little differently.

       #include <iostream> #include <iomanip> #include <cmath> int main() { using namespace std; int e, n; float s, t2, t2fmod; cout << "vvedite n \n"; cin >> n; s = n / 100 ; t2 = (n % 100) / 10.0; // (int) / (float) = (float); или static_cast<float>(10) -- глупо // или t2fmod = fmod(n, 100) / 10; // (float) / (int) = (float); e = n % 10; cout << "number one = " << s << endl; cout << "number two = " << fixed << setprecision(1) << t2 << "(" << t2fmod << ")" << endl; cout << "number three = " << e << endl; } 

      Explicit C (type)variable specific type conversions ( (type)variable ) are undesirable in C ++. It is better to use * _cast operations.