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;
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;
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;
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