Simple C++ program to calculate truncation – trunc(x, n) function.
#include <iostream> #include <cmath> using namespace std; // 2018 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net double trunc(double x, int n); int main() { double x = 0; int n = 0; cout << "Enter x: "; cin >> x; cout << "Enter n: "; cin >> n; cout << "trunc(" << x << ", " << n << ") is equal to " << trunc(x, n); int a; cin >> a; return 0; } double trunc(double x, int n) { return x > 0 ? floor(pow(10, n) * x) / pow(10, n) : ceil(pow(10, n) * x) / pow(10, n); }
IN 5.1423 2 -5.1423 2 OUT 5.14 -5.14
C++ Truncation trunc(x, n)