D
D
Denis Kuznetsov2019-04-16 14:37:36
C++ / C#
Denis Kuznetsov, 2019-04-16 14:37:36

How to get a fractional number when dividing 1 by 1?

i have a code

#include <iostream>

using namespace std;

int main() {
  int i = 1;
  int j = 1;

  cout << 1.0 * i / j << endl;

  system("pause");
  return 0;
}

if i = 9, j = 4, then everything is fine and I get a fraction, but when I try to get 1.0 it just displays 1

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman, 2019-04-16
@DennisKingsman

you can do explicit data type conversion in
program code:

#include <iostream>

using namespace std;

int main() {
  int i = 1;
  int j = 1;
  cout << fixed;
  cout << (float)(j/j) << endl;

  return 0;
}

compile and execute:
[email protected]:~/temp> gcc test.cpp -lstdc++  -o test.o
[email protected]:~/temp> ./test.o
1.000000

R
Roman, 2019-04-16
@myjcom

See what you need.

#include <iostream>
#include <iomanip>
#include <cstdlib>

int main()
{
  int a = 9;
  int b = 4;
  std::div_t result = div(a, b);
  std::cout << result.quot << " " << result.rem << std::endl;
  // Наверное это
  std::cout.precision(1);
  std::cout << std::fixed << static_cast<double>(a) / b << std::endl;
}

M
Max Goncharenko, 2019-04-16
@reverse_kacejot

The type of your expression is double.
This can be checked in a very simple way (I did this):
create a template class declaration without an implementation and instantiate it with an expression. The compilation error will show the type:

template <typename T>
class TD;

int main() {
    int i = 1;
    int j = 1;

    TD<decltype (1.0 * i / j)> td;
}

Mistake:
/home/maxim/Workspace/my/cdm/main.cpp: In function ‘int main()’:
/home/maxim/Workspace/my/cdm/main.cpp:61:32: error: aggregate ‘TD<double> a’ has incomplete type and cannot be defined
     TD<decltype (1.0 * i / j)> a;

As you can see, the type is displayed as double

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question