How to output fraction instead of decimal number?

后端 未结 13 2093
余生分开走
余生分开走 2020-12-01 21:59

In C++, When I calculate 2/3, it will output decimal values, how can I just get the original format (i.e.g 2/3) instead of 0.66666667

Thanks

13条回答
  •  误落风尘
    2020-12-01 22:40

    I am beginner and this way that I use may not be a proper way

    #include 
    
    using namespace std;
    int main ()
    {
      double a;
      double b;
      double c;
    
      cout << "first number: ";
      cin >> a;
      cout << "second number: ";
      cin >> b;
    
      c = a/b;
      cout << "result is: " << c << endl;
    
      if (b != 0) {
        if (a > 0) {
          if (c - (int)c > 0 && c - (int)c < 1)
            cout << "fraction: " << a << "/" << b;
        } else {
          if (c - (int)c < 0 && c - (int)c < 1)
            cout << "fraction: " << a << "/" << b;
        }
      }
    
      return 0;
    }
    

提交回复
热议问题