-1

I am new in C++. I am trying to divide "1" and "2". I want to round the result to thousandths (3 decimals) using setprecision. I have tried to do that, but unsuccessfully. What should I change in my code so that I get the result that I want?

My code:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    float a;
    float b;
    cout << "1: ";
    cin >> a;
    cout << "2: ";
    cin >> b;
    float result = a/b;

    cout << a << " / " << b << " = " << result << setprecision(3) << endl;
}
Deumaudit
  • 978
  • 7
  • 17
Daniel
  • 1
  • `setprecision` affects how numbers are **printed**, it has no effect on how calculations are done. `1.0` divided by `2.0` is always going to be `0.5`. – john Dec 06 '22 at 10:45
  • Does this answer your question? [Show two digits after decimal point in c++](https://stackoverflow.com/questions/16280069/show-two-digits-after-decimal-point-in-c) – ColdIV Dec 06 '22 at 10:48
  • 3
    Now that I've looked at your code (please include code in the question, not everyone bothers to follow links, I didn't at first) the problem is that you put `setprecision(3)` after the variable, when it should have been before. – john Dec 06 '22 at 10:51
  • Welcome to StackOverflow. Please take a [tour] and see [ask]. Specifically you should post your code for a [mre] as text in your question (not as an image or a link). – wohlstad Dec 06 '22 at 10:56
  • Aside, whenever you want to do `endl`, instead you probably should do `"\n"`. The `endl` token does a *newline* (which is clearly what you want), and **also** a *flush* (which is unlikely to be what you want). – Eljay Dec 06 '22 at 13:11

1 Answers1

0

Try running this

#include <iostream>
#include <iomanip>

int main()
{
    double a = 2;
    double b = 7;
    double value = a / b;
    std::cout << std::fixed << std::setprecision(3) << std::setw(10) << value << std::endl;
    return 0;
}

You can run it here https://www.programiz.com/cpp-programming/online-compiler/

Gandalf
  • 1
  • 29
  • 94
  • 165