1

I want to set the precision to max 2 or three for the variable correctAnswer. I dont want to format the output but store in the memory with max 3 precision. Both a and b are integer values.

double correctAnswer = static_cast<double>(a) / b;

2 Answers2

2

You can't set a precision for a cast. But you can for the output

double d = 3.14159265358979;
std::cout.precision(3);
std::cout << "Pi: " << std::fixed << d << std::endl;
user2393256
  • 1,001
  • 1
  • 15
  • 26
1

You can use integer arithmetic for that:

const int precision = 100;
double correctAnswer = precision * a / b / static_cast<double>( precision );

you need to make sure that precision * a still fits to int or use bigger type and when you compare/output correctAnswer you still need to handle double properly

Slava
  • 43,454
  • 1
  • 47
  • 90