Is there a way to round to the nearest number in the Boost library? I mean any number, 2's, 5's, 17's and so on and so forth.
Or is there another way to do it?
You can use lround available in C99.
#include <cmath>
#include <iostream>
int main() {
cout << lround(1.4) << "\n";
cout << lround(1.5) << "\n";
cout << lround(1.6) << "\n";
}
(outputs 1, 2, 2).
Check your compiler documentation if and/or how you need to enable C99 support.
Boost Rounding Functions
For example:
#include <boost/math/special_functions/round.hpp>
#include <iostream>
#include <ostream>
using namespace std;
int main()
{
using boost::math::lround;
cout << lround(0.0) << endl;
cout << lround(0.4) << endl;
cout << lround(0.5) << endl;
cout << lround(0.6) << endl;
cout << lround(-0.4) << endl;
cout << lround(-0.5) << endl;
cout << lround(-0.6) << endl;
}
Output is:
0
0
1
1
0
-1
-1
int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;
You actually don't need Boost at all, just the C library included in the C++ library. Specifically, you need to include the cmath header:
Round up a number: ceil(): http://www.cplusplus.com/reference/clibrary/cmath/ceil/
Round down a number: floor(): http://www.cplusplus.com/reference/clibrary/cmath/floor/
You can write your own round function then:
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>
double roundFloat(double x)
{
double base = floor( x );
if ( x > ( base + 0.5 ) )
return ceil( x );
else return base;
}
int main()
{
std::string strInput;
double input;
printf( "Type a number: " );
std::getline( std::cin, strInput );
input = std::atof( strInput.c_str() );
printf( "\nRounded value is: %7.2f\n", roundFloat( input ) );
return EXIT_SUCCESS;
}
Related
I am trying to write a function for cumulative distribution function taken from here.
This is my cpp code:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );
}
int main() {
cout << normalCDF(4.8) << endl;
cout << normalCDF(5.4) << endl;
cout << normalCDF(5.6) << endl;
cout << normalCDF(5.8) << endl;
cout << normalCDF(5.1) << endl;
cout << normalCDF(-37.5) << endl;
cout << normalCDF(-36.0) << endl;
cout << normalCDF(-37.6) << endl;
cout << normalCDF(-37.5) << endl;
return 0;
}
This is the output when compiled in linux with gcc 6.3.0
0.999999
1
1
1
1
0
0
0
0
I wanted to call same code from raku using NativeCall, so I modified code
test.cpp
extern "C" double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );
}
created dynamic shared .so library and wrote nativecall code as:
use NativeCall;
sub normalCDF(num64) returns num64 is native('libtest.so') { * };
say normalCDF((4.8).Num);
say normalCDF((5.4).Num);
say normalCDF((5.6).Num);
say normalCDF((5.8).Num);
say normalCDF((5.1).Num);
say normalCDF((-37.5).Num);
say normalCDF((-36.0).Num);
say normalCDF((-37.6).Num);
say normalCDF((-37.5).Num);
The output is:
0.999999206671848
0.9999999666795515
0.9999999892824097
0.9999999966842541
0.9999998301732593
0
0
0
0
Why is the output of same algorithm differing, though the data containers are used as recommended.
System information:
Ubuntu 18.04 64bit with gcc 6.3.0
Rakudo is 2019.07.1 version.
You need to print the floating point numbers with increased precision. The following will give you the maximum precision:
#include <limits>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );
}
int main() {
typedef std::numeric_limits< double > dmax;
cout.precision(dmax::max_digits10);
cout << normalCDF(4.8) << endl;
cout << normalCDF(5.4) << endl;
cout << normalCDF(5.6) << endl;
cout << normalCDF(5.8) << endl;
cout << normalCDF(5.1) << endl;
cout << normalCDF(-37.5) << endl;
cout << normalCDF(-36.0) << endl;
cout << normalCDF(-37.6) << endl;
cout << normalCDF(-37.5) << endl;
return 0;
}
Notice the #include <limits> and the first two lines in main, although line 2 is what matters.
I have to write a program to test an integer value to determine if it is odd or even, and make sure my output is clear and complete. In other words, I have to write the output like "the value 4 is an even integer". I was also hinted that I have to check the value using the remainder modulo.
The issue I have is with the scanf() function. I get a syntax error:
'%=' expected a ')'
How do I fix this?
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main()
{
int number = 0;
cout << "enter an integer ";
int scanf(%=2 , &number);
if (number == 0)
cout << "the value" << number << "is even";
else
cout << "the value" << number << "is odd";
return 0;
}
You are using scanf() incorrectly (read the scanf() documentation on cppreference.com). The first parameter expects a null-terminated string containing the format to scan, but you are not passing in anything that even resembles a string. What you are passing in is not valid string syntax, per the C++ language standard. That is why you are getting a syntax error.
You need to change this line:
int scanf(%=2 , &number);
To this instead:
scanf("%d", &number);
Though, in C++ you really should be using std::cin instead for input (you are already using std::cout for output):
std::cin >> number;
Try this:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int number = 0;
cout << "enter an integer ";
if (cin >> number)
{
if ((number % 2) == 0)
cout << "the value " << number << " is even";
else
cout << "the value " << number << " is odd";
}
else
cout << "the value is invalid";
return 0;
}
I know this question is a little dated, however, if you are able to use modern C++ features. You can write a constexpr helper function such as this:
#include <cstdint>
constexpr bool isEven(uint32_t value) {
return ((value%2) == 0);
}
Then in your main function, you can traverse through a loop of N integers and output your display such as:
#include <iostream>
#include <iomanip>
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << " is "
<< (isEven(i) ? "even" : "odd") << '\n';
}
return 0;
}
It's literally that simple. Here's another nice feature of using the constexpr helper function... You can also format your output as such:
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << ": "
<< std::boolalpha << isEven(i) << '\n';
}
return true;
}
If you are looking for something that is more efficient than using the modulo operator you can bitwise & with the least significant digit... The code above would then become:
#include <cstdint>
constexpr bool isOdd(uint32_t value) {
return (value&1);
}
And using it would be very similar as above, just make sure you reverse the wording in your output to match that from the function being used...
#include <iostream>
#include <iomanip>
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << " is "
<< (isOdd(i) ? "odd" : "even") << '\n';
}
return 0;
}
Again you can use the std::boolalpha manipulator to get this kind of output:
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << ": "
<< std::boolalpha << isOdd(i) << '\n';
}
return true;
}
Im working on a college project and it requires big number like 43,000,000 but everytime i launch the program it gives me something like this 43000,000. I already used std::fixed and precision but it doesnt add the second comma.
this is the code:
double PreEnCol() {
if (marca == 1)
return (105.000*562);
else if (marca == 2)
return (65.000*562);
else if (marca == 3)
return (54.000*562);
else if (marca == 4)
return (125.000*562);
else if (marca == 5)
return (129.000*562);
else if (marca == 6)
return (85.900*562);
}
string toString(){
stringstream s;
s << endl;
s << std::fixed << std::setprecision(1) << "Precio en colones: "<<PreEnCol() << endl;
return s.str();
}
Please i need help with this i've been dealing with this problem for hours.
Mostly your output depend on your default locale. You need to override you whole locale OR part of locale of you interest.
Below code helps you to override part of locale which is responsible for printing commas in number.
#include <iostream>
#include <sstream>
#include <iomanip>
#include <locale>
struct Sep3Digit : std::numpunct<char> {
std::string do_grouping() const { return "\003"; }
};
std::string FormatWithCommas(double d)
{
std::stringstream ss;
ss.imbue(std::locale(std::cout.getloc(), new Sep3Digit));
ss << std::fixed << d;
return ss.str();
}
int main()
{
std::cout<<FormatWithCommas(std::numeric_limits<double>::max())<<std::endl;
return 0;
}
You can usually do that with default system locale:
#include <locale>
string toString(){
stringstream s;
s << endl;
s.imbue(std::locale("")); // <-- set locale. OR: std::locale("en_US")
s << std::fixed << std::setprecision(1) << "Precio en colones: "<<PreEnCol() << endl;
return s.str();
}
Note that this will print 43000000 as 43,000,000 in some parts of the world, or as 43.000.000 in others where '.' is used as grouping separator.
Here's full example:
#include <locale>
#include <string>
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
string toString(int n)
{
stringstream s;
s << endl;
s.imbue(std::locale("")); // <-- set locale
s << std::fixed << std::setprecision(1) << "Precio en colones: "<< n << endl;
return s.str();
}
int main()
{
int n = 43000000;
cout << "formatted " << n << ": " << toString(n) << endl;
}
It produces this output:
formatted 43000000:
Precio en colones: 43,000,000
I need some help. I want to achieve a result as shown on my image result
first question... did my teacher make a mistake? 2^10 = 1024 and not 2048... ?! but nvm..
my only problem is the cout of numbers over 100.000 - please help
here's my code so far
#include <iostream>
#include <math.h>
#include <iomanip>
#include <string>
#include <sstream>
#include <ostream>
#include <stdio.h>
#include <conio.h>
#include <fstream>
using namespace std;
int main() {
int p; // exponent
float b; // base
cout << setw(4);
for (b=1; b<11; b++) {
cout << " | " << setw(12) << b;
}
cout << endl;
for (b=1; b<=10; b++) {
cout << b;
for (p=1; p<=10; p++) {
cout << " | " << setw(12) << pow(b, p);
}
cout << endl;
}
return 0;
}
Output of this is here
pls pls help,
best regards!
If the issue is output, then the easiest thing to do is cast the pow() return value to a long long or whatever your compiler's 64-bit int type is.
This will automatically use the long long overload for operator <<, which will effectively remove the scientific notation.
for (p=1; p<=10; p++) {
cout << " | " << static_cast<long long>(pow(b, p));
Live Example
I would like to see whether it is possible to see all values that we have emplaced. For example:
#include <iostream>
#include <unordered_map>
using namespace std;
int main () {
unordered_multimap<string,int> hash;
hash.emplace("Hello", 12);
hash.emplace("World", 22);
hash.emplace("Wofh", 25);
for (int i = 1; i < 10; i++) {
hash.emplace("Wofh", i);
}
cout << "Hello " << hash.find("Hello")->second << endl;
cout << "Wofh " << hash.count("Wofh") << endl;
cout << "Wofh " << hash.find("Wofh")->second << endl;
return 0;
}
The output is :
$ ./stlhash
Hello 12
Wofh 10
Wofh 9
Whereas I want the last line to show from 25,1,2... to 9. Apparently find only takes first and second pointer as first is the value and second is the corresponding value. Is there any way to do this?
The operation you need is called equal_range
Example from the cplusplus.com:
// unordered_multimap::equal_range
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
typedef std::unordered_multimap<std::string,std::string> stringmap;
int main ()
{
stringmap myumm = {
{"orange","FL"},
{"strawberry","LA"},
{"strawberry","OK"},
{"pumpkin","NH"}
};
std::cout << "Entries with strawberry:";
auto range = myumm.equal_range("strawberry");
for_each (
range.first,
range.second,
[](stringmap::value_type& x){std::cout << " " << x.second;}
);
return 0;
}