Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Arithmetic Operations | Introduction
C++ Data Types

book
Arithmetic Operations

Setting the precision

As you already should know you can perform basic data manipulation using arithmetic operators such as addition (+), subtraction (-), division (/), and multiplication (*). Additionally, the modulus operator (%) calculates the remainder of a division.

cpp

main

copy
#include <iostream>
#include <iomanip>

int main()
{
// Uncomment to see the difference
// std::cout << std::fixed;
std::cout << std::setprecision(5) << 15.125 * 0.8309 << std::endl;
}
123456789
#include <iostream> #include <iomanip> int main() { // Uncomment to see the difference // std::cout << std::fixed; std::cout << std::setprecision(5) << 15.125 * 0.8309 << std::endl; }

In the example above, floating-point results may occasionally be produced during calculations. To manage the precision of these results, you can use std::setprecision in combination with std::fixed. This allows you to control the number of digits displayed after the decimal point, ensuring consistent precision in your output.

Note

Without std::fixed, std::setprecision controls the total number of digits displayed, including both before and after the decimal points. With std::fixed, the number is displayed in fixed-point notation, keeping the decimal point in a fixed position.

Taak

Swipe to start coding

  1. Include <iomanip> to be able to set precision.
  2. Follow the comments to set a precision.
  3. Calculate and output the equivalent of 5 miles in kilometers rounding to one decimal place.

Note

To convert 5 miles to kilometers, you would multiply the number of miles by the conversion factor (1.60934).

Oplossing

cpp

solution

#include <iostream>
#include <iomanip>
int main()
{
// Use std::fixed to set precision for digits only after the decimal
// To set the precision to the 1 you have to use std::setprecision(1)
// Make sure to add it after std::cout << and before expression
std::cout << std::fixed << std::setprecision(1) << 5 * 1.60934 << std::endl;
}
Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 1. Hoofdstuk 2
#include <iostream>
#include <___>

int main()
{
// Use std::fixed to set precision for digits only after the decimal
// To set the precision to the 1 you have to use std::setprecision(1)
// Make sure to add it after std::cout << and before expression
std::cout << ___ << ___(_) << 5 * ___ << std::endl;
}

Vraag AI

expand
ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

some-alt