How to read the entire value of a double using cin? - c++

long double m;
cout << "enter double: "; cin >> m;
cout << "m = " << m <<endl;
Input:
enter double: 1.546640625
Output:
m = 1.54664
I have to convert into a binary with point, and when I read numbers like 2.359375000
Output:
m = 2.35938
And it works, but I think the problem is the zero in 1.546640625

You have read the whole value of the double. The problem is with the cout. It by default rounds the value to 6 digits after the decimal point.
To set the precision cout uses, use setprecision from <iomanip>:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
long double d;
cin >> d;
cout << setprecision(10) << d << endl;
return 0;
}

Related

How can a floating-point number be printed with more precision?

So i was attempting to code this question Link and i developed the logic and i started coding it. The code is shown below, but there is an issue with it. When i gave the code the following input (Image 1), the output came out to be 2.22582e+007, whereas the correct accepted output is 22258199.500000. What changes should i make in the data type to amend this error. How can i change the notation. Please bear with me as my knowledge of data types is limited.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n,l;
cin >> n;
cin >> l;
vector<float> v;
vector<float> b;
for(int i=0; i<n; i++){
int x;
cin >> x;
v.push_back(x);
}
sort(v.begin(),v.end());
if(v[0]!=0){
b.push_back(v[0]);
for(int i=1; i<n; i++){
b.push_back((v[i] - v[i-1])/2.0);
}
}else if(v[0] == 0){
for(int i=1; i<n; i++){
b.push_back((v[i] - v[i-1])/2.0);
}
}
sort(b.begin(), b.end());
cout << b[b.size()-1];
}
You can use std::cout << std::setprecision(std::numeric_limits<float>::max_digits10) to output the value in a round-trippable format. (This will need headers <limits> and <iomanip>).
If that doesn't work, try also replacing float with double.
You're going to want to use iomanip.
#inlcude <iomanip>
cout<<fixed<<setprecision(6)
fixed will disable the scientific notation.
setprecision will allow you to be as precise as you want.
This resolved the issue.
link
The issue primarily was that the notation of the output was scientific and sometimes the online judges do not accept that, hence to change the notation from scientific to fixed and to other forms, the following code snippet can be used.
Either you can increase the precision or you can change the notation. Either of the latter cases can help.
#include <iostream>
#include <sstream>
int main()
{
std::cout << "The number 0.01 in fixed: " << std::fixed << 0.01 <<
'\n'
<< "The number 0.01 in scientific: " << std::scientific <<
0.01 << '\n'
<< "The number 0.01 in hexfloat: " << std::hexfloat << 0.01
<< '\n'
<< "The number 0.01 in default: " << std::defaultfloat <<
0.01 << '\n';
double f;
std::istringstream("0x1P-1022") >> std::hexfloat >> f;
std::cout << "Parsing 0x1P-1022 as hex gives " << f << '\n';
}
output of the given code - click here

C + + Can I use arrays here to shorten my code?

This is my first post on here so please don't kill me for my noobishness.
I recently made a program for fun to put in a ton of numbers and have it put out the mean, not very useful but I thought I would see if I could. I would love it if someone could explain to me how I could improve my code using arrays instead of lots of variables, but still achieve the same thing, maybe even more efficiently.
My code looks like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int q1;
int q2;
int q3;
int q4;
int q5;
int q6;
int q7;
int q8;
int q9;
int q10;
int q11;
int q12;
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
cin >> q1;
cin >> q2;
cin >> q3;
cin >> q4;
cin >> q5;
cin >> q6;
cin >> q7;
cin >> q8;
cin >> q9;
cin >> q10;
cin >> q11;
cin >> q12;
f = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12;
cout << f / a << '\n';
system("pause");
}
Any advice is very appreciated! This was made in Visual Studio just in case you needed to know.
Of course arrays can make your life easier!
Here's how you could have accomplished the same task as above, with arrays:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "You can only enter up to 12 numbers;
// Declare an array to hold 12 int's
int nums[12];
// i will count how many numbers have been entered
// sum will hold the total of all numbers
int i, sum = 0;
for(i = 0; i < 12; i++) {
cout << "Enter the next number: ";
cin >> nums[i];
sum += nums[i];
}
cout << "The mean is: " << (sum / totalNums) << '\n';
//Try to avoid using system!
system("pause");
}
But, why use an array?
There's no need to keep any of the numbers after you add them to the total, so why use an array?
You can accomplish the same task without an array and with only one variable for the numbers!
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "Enter the amount of numbers that will be entered: ";
cin >> totalNums;
// i will count how many numbers have been entered
// sum will hold the total of all numbers
// currentNum will hold the last number entered
int i, sum = 0, currentNum = 0;
for(i = 0; i < totalNums; i++) {
cout << "Enter the next number: ";
cin >> currentNum;
sum += currentNum;
}
cout << "The mean is: " << 1.0 * sum / totalNums << '\n';
//Try to avoid using system!
system("pause");
}
Arrays can be considered as series of variables each of which has ids.
integers between 0 and (number of elements) - 1 (both inclusive) are available ids.
Using that with loop, your code can be like this (sorry, I hate stdafx.h):
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int q[12];
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
for (int i = 0; i < 12; i++) {
cin >> q[i];
}
f = 0;
for (int i = 0; i < 12; i++) {
f += q[i];
}
cout << f / a << '\n';
system("pause");
}
You may use the numbers read in the future, but currently the numbers aren't used except for calculating the sum, so you can omit the array and do addition while reading. Also I deleted the variable t, which is unused and stopped using using namespace std;, which is not considered as good.
#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
int main() {
int q;
int f;
//Used for the total of all values
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
f = 0;
for (int i = 0; i < 12; i++) {
cin >> q;
f += q;
}
cout << f / a << '\n';
system("pause");
}
You marked this question as C++.
I recommend you do not use "using", and you should prefer vector over array.
Consider the following approach:
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
std::cout << "We will be finding a mean." << std::endl
<< "Enter numbers, and press ^d when complete.\n"
<< std::endl;
// Declare a vector to hold user entered int's
std::vector<int> intVec;
// the vector automatically keeps track of element count
do {
std::cout << "number: "; // prompt
int t = 0;
std::cin >> t; // use std::cin,
if(std::cin.eof()) break; // ^d generates eof()
intVec.push_back(t);
}while(1);
// there are several way to sum a vec,
// this works fine:
int sum = 0;
for (auto i : intVec) sum += i;
std::cout << "\n sum : " << sum
<< "\ncount : " << intVec.size()
<< "\n mean : " << (sum / intVec.size()) << std::endl;
return(0);
}
You can enter single item per line (neatness counts).
You can enter multiple integers separated by white space, but the above will give back a prompt for the integers already entered.
^d - generates an end of file input.
... press and hold 'Control' key and letter 'd' at same time
Note - does not handle error input - try entering a 'number' as 'num' string.
The accepted answer is definitely the most efficient way to transform your code using arrays, but one thing I would add is that in C++ dividing an integer by another integer can only ever result in an integer, and because you're trying to get the mean, it seems like you'd want to have the result in decimals, so you need to do one of two things:
Declare sum as a float for the purposes of diving it by totalNums to get the mean.
Cast one of the integers to either a float or a double so that the decimals won't get truncated, so the last cout statement would look like this:
cout << "The mean is: " << (double)sum/totalNums << endl;
In C++ the default for precision is 6, but you can change the number of decimal points that are displayed by adding #include <iomanip> and using the setprecision( ) function in the iomanip, which you can just add in the same output line:
cout << setprecision(x) << "The mean is: " << (double)sum/totalNums << endl;
where x is whatever precision you want.
If you want to try using dynamic memory
This is definitely not necessary for what you're doing, but it's interesting stuff and good practice!
One more thing is that if you want to be able to have the user enter integers indefinitely, you can dymanically allocate memory during runtime by declaring a array of pointers to integers (so it's an array of address locations instead of an array of integers) and some sentinal value so they can decide when to stop. That code would look like:
#include <iostream>
#include <iomanip>
using namespace std;
main( ) {
const int ARRAY_SIZE = 200;
const int SENTINAL = -999;
int totalNums = 0;
int sum = 0;
//declare an array of pointers to integers so
//the user can enter a large number of integers
//without using as much memory, because the memory
//allocated is an array of pointers, and the int
//aren't allocated until they are needed
int *arr[ARRAY_SIZE];
cout << "We will be finding a mean." << endl;
cout << "Enter integers (up to 200) or enter -999 to stop" << endl;
//add a conditional into the for loop so that if the
//user enters the sentinal value they will break out
//of the loop
for (int c = 0; c < ARRAY_SIZE; c++) {
//every time you iterate through the loop, create a new
//integer by using the new keyword using totalNums as
//the index
arr[totalNums] = new int;
cout << "Enter integer: ";
//input into the array of pointers by dereferencing it
//(so it refers to what the pointer is pointer to instead
//of the pointer)
cin >> *arr[totalNums];
if (*arr[totalNums] == SENTINAL)
break;
else {
sum += *arr[totalNums];
totalNums++;
}
}
cout << setprecision(3) << "The mean is: " << (float)sum / totalNums << endl;
}

Adding a Probability Equation Into the Program

I've been working on this program in which it should calculate the probability based on the following formula:
𝑃(𝑥) = (𝑁!) / (𝑥!) * (𝑁−𝑥)!) * (p^x) * ((1-p)^(N-x))
Also, when the user types in a value, N must be an integer, x must be an integer which can be between 0 and N, and p must be a positive real number between 0 and 1. Till now this part works just fine but I don't know how to properly add the probability formula in the program.
The following is my code so far:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
long int factorial (int N, int x, int p);
int main ()
{
double N, x, p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
return 0;
}
Can anyone help me out just to understand how to properly add an equation in my program?
Thank you!
This is my new code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double factorial (double N, double x, double p);
int main ()
{
double N;
double x;
double p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
double Probability;
Probability = factorial(N, x, p);
cout << "Probability= " << Probability << endl;
return 0;
}
double factorial (double N, double x, double p){
double answer = ((tgamma(N+1))/((tgamma(x+1)) * (tgamma((N-x)+1)))) * (pow(p,x)) * (pow((1-p),(N-x)));
return answer;
}
The program recognizes the values I put in the system but when it calculates the answer, it gives a really small number. I tried out each section of the formula to make sure their was not a mistake but everything works fine when I tested it independently. Does anyone know what's wrong with the equation?
Thank you!
First you need to write a factorial function, check out this stackoverflow link:
How do you implement the factorial function in C++?
Then just write a function for your calculation. Assuming your factorial function is called getFact(int n) then:
double solve(int N, int x, double p) {
double answer = ( getFact(N)/getFact(x) )*getFact((N-x))* pow(p,x)* pow((1-p),(N-x));
return answer;
}
Then call the solve function in your main after having set your values.
double P_x;
P_x = solve(N,x,p);
Also, I use doubles because they can be more accurate, especially for p since its is 0 <= p <= 1.

Currency Conversion Program

I'm working on a currency converter program that converts the old system of British pounds, Shillings, and pence, into their new system, which is a type of Decimal Pound. Where 100 pence equals a pound. Here is the code for the program
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int calcNum(int pound, int shilling, int pence)
{
pence = pound*240 + shilling*12 + pence;
return pence;
}
int calcNew(int total_pence, double dec_pound)
{
dec_pound = total_pence / 240;
return dec_pound;
}
int main()
{
int pence;
int shilling;
int pound;
const int OLD_POUND = 240;
const int OLD_SHILLING = 12;
double total_pence;
double dec_pound = 0;
double deci_pound;
cout << "Please Enter the Amount of old pounds: ";
cin >> pound;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old shillings: ";
cin >> shilling;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old pence: ";
cin >> pence;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);
cout << (5, "\n");
cout << "The total amount in decimal pounds is: ";
cout << setprecision(2) << "\x9c" << deci_pound;
_getch();
return 0;
}
When I run this program however, I'm having a bit of a problem. No matter what the number input is, it always says 0 pounds. Just to make sure that the setprecision function at the end wasn't interfering with the code, I had originally set a cout statement with a _getch() after the two functions to show how much deci_pound came out to be calculated to, and once again, it came out as zero. So my issue seems to be somewhere in the functions running the calculations. If someone could help me with this, I would really appreciate it.
Your calcNew(...) function returns an int, make it return a double. Right now it casts to int which involves stripping the decimals.
In your code, dec_pound is set equal to zero, and you're deci_pound = calcNew(dec_pound, total_pence), which divides 0 by 240 = 0.
The order of the parameters when you call both functions is wrong. Your functions are declared and implemented as:
int calcNum(int pound, int shilling, int pence);
int calcNew(int total_pence, double dec_pound);
And then you call them like this:
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);

Why does setf(ios::fixed) skip the 6th number in a double?

#include <iostream>
using namespace std;
int main() {
double pi = 0.1234567;
cout << "1234567890" << endl;
// cout.width(10);
cout.setf(ios::fixed);
cout << pi << endl;
}
outputs
1234567890
0.123457
Why does it print that instead of 0.123456?
Because it rounds it correctly, that's why. 0.1234567 rounded to 6 decimal places (the default) is 0.123457.