I have a C++ problem:
#include<iostream>
#include<stdio.h>
using namespace std;
int main() {
double k = 1.2366;
cout << printf("%.3lf\n", k);
}
the output is:
1.237
6
but I expect:
1.237
why do i get this additional 6 at the 2nd line ?
Well, you first call printf that prints out the number and then stream the result of printf (the number of characters printed) to cout.
This is because printf returns the number of printed characters. To get your code right, simply use std::cout directly with the desired precision:
std::cout << fixed << setprecision(3);
std::cout << k << "\n";
If you want to round results, read How do you round off decimal places in C++? which points you to e.g. floor/ceil/round. But take care to not round the value itself, if you use it again.
Related
I am working on below code:
#include<iostream>
#include<stdio.h>
using namespace std;
main() {
unsigned char a;
a=1;
printf("%d", a);
cout<<a;
}
It is printing 1 and some garbage.
Why cout is behaving so?
cout << a is printing a value which appears to be garbage to you. It is not garbage actually. It is just a non-printable ASCII character which is getting printed anyway. Note that ASCII character corresponding to 1 is non-printable. You can check whether a is printable or not using, std::isprint as:
std::cout << std::isprint(a) << std::endl;
It will print 0 (read: false) indicating the character is non-printable
--
Anyway, if you want your cout to print 1 also, then cast a to this:
cout << static_cast<unsigned>(a) << std::endl;
I had a similar issue here that I've long forgotten about. The resolution to this problem with iostream's cout can be done like this:
#include<iostream>
#include<stdio.h>
main() {
unsigned char a;
a=1;
printf("%d", a);
std::cout<< +a << std::endl;
return 0;
}
instead of casting it back to another type if you want cout to print the unsigned char value as opposed to the ascii character. You need to promote it.
If you noticed all I did was add a + before the unsigned char. This is unary addition that will promote the unsigned char to give you the actual number representation.
User Baum mit Augen is responsible for reminding me of this solution.
You need to typecast a as integer as cout<< (int)(a);. With this you will observe 1 on the output. With cout << a;, the print will be SOH (Start of Heading) corresponding to ascii value of 1 which can't be printed and hence, some special character is observed.
EDIT:
To be more accurate, the cout statement should be cout << static_cast<unsigned>(a) as Nawaz has mentioned.
The C compiler has its own way of defining the type of the printed output, because you can specify the type of the output.
Ex:
uint8_t c = 100;
printf("%d",c);
so you can also print c as an int by %d, or char %c, string %s or a hex value %x.
Where C++ has its own way too, the cout prints the 8-bit values as a char by default. So, you have to use specifiers with the output argument.
You can either use:
a + before the name of the output argument
uint8_t data_byte = 100;
cout << "val: " << +data_byte << endl;
use a function cast unsigned(var); like,
uint8_t data_byte = 100;
cout << "val: " << unsigned(data_byte) << endl;
printf("%u",a);
its so simple try it
how to print specific number of digits in c++?For example ,printing 8 digits totally(before and after decimal point combined)
Edit: For further clarification, setprecision sets the digits when i have decimal digits to display.I want to display integer 30 also as 30.000000 ,in 8 digits.
The setprecision command puts fixed no. of digits after decimal and i don't want that.
In short , I want an alternative of c command printf("%8d",N) in C++.
You can do it using setprecision() function from include iomanip and fixed like:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double d = 1000;
double t = d;
int dc=0;
while(t>0.9)
{
dc++;
t= t/10;
}
cout<<"dc:"<<dc<<endl;
cout << fixed;
std::cout << std::setprecision(dc);
std::cout << d;
return 0;
}
The setprecision() will not work fine every time So you have to use fixed as well.
You should use the c++ header iomanip what you want is the setprecision() function:
std::cout << std::setprecision(5) << 12.3456789 << std::endl;
outputs 12.346. It also has other modifiers you can find here
EDIT
If you want to print trailing 0s, you need to also use std::fixed. This says to use that number of digits, regardless of whether or not they are significant. If you want that to be the total number, you could figure out the size of the number, then change the precision you set it to based on that, so something like:
#include <iostream>
#include <iomanip>
#include <cmath>
int main()
{
double input = 30;
int magnitude = 0;
while(input / pow(10, magnitude))
{
++magnitude;
}
std::cout << std::fixed << std::setprecision(8 - magnitude) << input << std::endl;
return 0;
}
This returns 30.000000. You can also do something similar by outputting to a string, then displaying that string.
#include <iostream> using namespace std;
int main()
{
double x=5.0,y=4.0,z;
z=x+y;
cout<<x<<endl<<y<<endl<<z;
return 0;
}
The above program gives me the following output:
5
4
9
When I have declared the variables to be double and even z as double why do I get the output as integer value(9)??
cout is being helpful here: if the double value is a whole number, then it, by default, does not display a decimal separator followed by an arbitrary number of zeros.
If you want to display as many numbers as the precision that your particular double on your platform has, then use something on the lines of
cout.precision(std::numeric_limits<double>::max_digits10);
cout << fixed << x << endl;
Floating point numbers with no digits after the floating point are printed as integers by default.
To always show the floating point, use setiosflags(ios::showpoint).
You can combine that with fixed and setprecision(n) I/O flags to limit how many digits to print after the floating point. For example:
double d = 5.0;
cout << setiosflags(ios::showpoint) << d << endl; // prints 5.00000
cout << setiosflags(ios::showpoint) << fixed << setprecision(1)
<< d << endl; // prints 5.0
This question already has answers here:
How can I pad an int with leading zeros when using cout << operator? [duplicate]
(7 answers)
Closed 7 years ago.
In a C++ program, I want to display a column of floating point values so that the sign, digits, and decimal point all line up. Multiple leading zeros should pad the whole number part of each value, when necessary. For example:
A column of floating point values:
+000.0012
-000.0123
+000.1235
-001.2346
+012.3457
-123.4568
I had an elaborately commented test program that demonstrated the problem. But, as I was editing this post, I found the answer I need here:
- Extra leading zeros when printing float using printf?
The essential problem was that I was using a format code of "%+04.4f" when I should use "%+09.4f", because the total field width I want is 9:
1 for the sign
3 for the whole digits
1 for the decimal point
4 for the fractional digits
I do not have enough reputation points to comment on that post, so thank you from here, #AndiDog.
I still do not know how to get multiple leading zeros using just stream formatting flags. But that is a battle for another day. I will stick with a mixture of printf and stream for now.
A couple of comments have mentioned std::setfill('0') and std::setw. While these are necessary, they're not sufficient to the task. For example, this code:
std::cout << std::setfill('0') << std::setw(7) << std::showpos << 0.012;
will produce: 0+0.012 as its output. This is obviously not quite what we wanted.
We need to add the std::internal flag to tell the stream to insert "internal padding" -- i.e., the padding should be inserted between the sign and the rest of the number, so code like this:
std::cout << std::setfill('0') << std::setw(7) << std::internal << std::showpos << 0.012;
...produces the output we want: +00.012.
Also note that the padding character is "sticky", so if you alternate between using std::setw with numeric and non-numeric types, you'll probably need/want to change it each time. Otherwise, something like std::cout << setw(12) << name; will produce results like: 0000000Jerry, which is rarely desired either.
To assure that we always get the same number of places after the decimal point, we also need to set the std::fixed flag, and specify the number of places with std::setprecision, such as:
#include <iostream>
#include <iomanip>
#include <vector>
int main() {
std::vector<double> values { 0.1234, 1.234, 1.5555 };
for (auto d : values)
std::cout << std::internal << std::showpos << std::setw(9)
<< std::setprecision(3) << std::setfill('0') << d << "\n";
}
Which produces the output I believe is desired:
+0000.123
+0001.234
+0001.556
There is one circumstance under which you won't get aligned results this way though: if you have a number too large to fit into the field provided, all the places before the decimal point will still be printed. For example, if we added 1e10 to the list of numbers to be printed by the preceding code, it would be printed out as: +10000000000.000, which obviously won't align with the rest.
The obvious way to deal with that would be to just put up with it, and if it arises often enough to care about, increase the field size to accommodate the larger numbers.
Another possibility would be to use fixed notation only the number is below a certain threshold, and switch to (for example) scientific notation for larger numbers.
At least in my experience, code like this tends to be used primarily for financial data, in which case the latter option usually isn't acceptable though.
To show the positive sign, you use std::showpos.
To show the leading zeros, you use std::setw(n) and std::setfill('0').
To show the digits after zero, you use std::setprecision(m).
To show the zeros between the + sign and the first digit, you use std::internal.
To keep the digit at a fixed position, you use std::fixed.
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main () {
double f =1.234;
double g =-12.234;
std::cout << std::showpos<< std::internal << std::fixed << std::setprecision(4)<<std::setw(9) <<std::setfill('0') << f << '\n';
std::cout <<std::setw(9)<< std::setfill('0') <<g<<"\n"; //repeat these for a new number
return 0;
}
//output:
//+001.2340
//-012.2340
The only way I now how to do this is to display the sign first and then set the fill, width and precision after and display the positive value as you have already displayed the sign. You also need to set the format flag to ios::fixed
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float x[] = { 000.0012, .0123, .1235, 1.2346, 12.3457, 123.4568 };
cout.setf(ios::fixed);
for (int i = 0; i < 6; i++)
cout << (x[i] > 0 ? '+' : '-') << setfill('0') << setw(8) << setprecision(4) << abs(x[i]) << endl;
return 0;
}
Displays
+000.0012
-000.0123
+000.1235
-001.2346
+012.3457
-123.4568
when I am trying to run this snippet of code I am getting some malfunctions I have not been able to pinpoint the cause of. The first two "cout" lines display the numbers 7 and 3, however, the last "cout" line displays numbers ranging from 50-60 usually (At the moment when I run it I get 55 and 51, which seems to somehow correlate a bit with the numbers I am trying to read). As far as I can tell from some googling and the books I have at hand this should be valid, but there's obviously something I am missing. Thank you for your time.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "73";
int one=0, two=0;
cout << text.at(0) << endl;
cout << text.at(1) << endl;
one = text.at(0);
two = text.at(1);
cout << one << endl << two << endl;
return 0;
}
the program functions correctly: text.at() returns a char, which you implicitly convert to an int. Then you print the value of that int, which are respectively 55 for "7" and 51 for "3" (look here).