setprecision() not working as expected - c++

I was doing a program which first takes 2 numbers (with float datatype) from the user and then ask the user about up-to what digit he want's to get the number divided and finally divides it up-to that number and 'cout<<' it. It compiled but din't worked up-to the mark when I calculated 22/7 which is an irrational no. up-to 100 digits it just calculated up-to 30 or 40 digits and then rest of was filled with zeros. Something like this:
3.1428570747375488281250000000000000000000000000000000000000000000000000000000000000000000000000000000
Here is my code:
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
system("clear");
float y;
int z;
float x;
float a;
cout << "\nHello User\n";
cout << "\nEnter first num to be divided: ";
cin >> x;
cout << "\nCool!! Now enter the 2nd number: \n";
cin >> y;
cout << "\Exelent!! Enter the place upto which u wanna caculate: ";
cin >> z;
a = x / y;
cout << fixed << showpoint;
cout << setprecision(z);
cout << "Calculating......\n" << a << endl;
return 0;
}

Floating point types have certain precision. You don't get exact results when operating on floats (or doubles). Now to get a better precision use double instead of float (See this post for more details).
You could #include <limits>, remove the step that gets the precision from input and change your code to:
std::cout << std::setprecision(std::numeric_limits<float>::max_digits10);
to display the result with maximum precision for the type you use.

Related

How to get the correct amount of decimals using double in C++

Basically if I write 15.20 I want 15.20 to return and if I write without any extra zeros or any rounding so that the 0 is still printed out.
I tried using setprecision, but it just adds a bunch of zeros.
my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double flyttal;
cout << "Skriv in ett flyttal: ";
cin >> flyttal;
cout << "Du skrev in flyttalet: " << fixed << setprecision(2) << flyttal << endl;
return 0;
}
Now thats fine for the float value 15.20 but if I want to write 1.315456 I will only get 1.32. I want to be able to get the same amount of decimals as I put in.

Problem rounding numbers in C++ with a BMI calculator

I', trying to make a simple BMI calculator using C++. When I input my personal height and weight, I get the correct result but I can't round the number to the nearest whole number. I looked up some videos and some articles and many of them suggested using the "round()" function. I tried that and the result I got was 0!
All feedback helps. Thanks!
#include <iostream>
#include <cmath>
using namespace std;
float Calculate(float kilo, float centimeter)
{
float meter = centimeter * 100;
return kilo / (meter * meter);
}
int main()
{
float kilo, centimeter;
float bmi;
cout << "BMI calculator." << endl;
cout << "Please enter your weight in kilograms. ";
cin >> kilo;
cout <<"Please enter your height in centimeters. ";
cin >> centimeter;
bmi = Calculate(kilo, centimeter);
cout << round(bmi) << endl;
return 0;
}
Your formula for calculating BMI is wrong just change the line float meter = centimeter/100;.
because according to your formula any number multiplied by 100 and then squared becomes so big that you get very small floating point number after the division with weight that is eventually rounded that's why you always get 0 in output.

why does my calculator program start flashing and scrolling when i enter a large number

my program is a calculator that currently only does addition and subtraction, but when i input a large number it starts flashing and scrolling. it works fine for small numbers. the program isn't long so here it is. a youtube video of the problem https://youtu.be/Fa03WtgXoek
#include <iostream>
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
return a;
}
int add()
{
int x = GVFU();
int y = GVFU();
int z = x + y;
std::cout <<z <<std::endl;
return 0;
}
int subtract()
{
int x = GVFU();
int y = GVFU();
int z = x - y;
std::cout <<z << std::endl;
return 0;
}
int main()
{
for ( ; ; )
{
std::cout << "enter 1 for addition and 2 for subtraction";
int c;
std::cin >> c;
if (c==1)
{
add();
}
if (c==2)
{
subtract();
}
std::cout << "press 1 to end";
int e;
std::cin >>e;
if (e==1)
{
return 0;
}
}
}
If you try to read a value from cin and the value read doesn't match the expected format, it causes the stream to fail and all future read operations will instantly return without reading anything.
Independently, in C++ integer values for the int type have a minimum and maximum possible value that depends on what compiler and system you're using. If you exceed that value when entering a number, cin will consider it a failed read.
Putting this together, once you enter a value that's too large, the program will keep running through the main loop in your program, prompting for a value, instantly returning without actually getting user input, then calculating garbage values.
To fix this, you'll need to either (1) just hope the user doesn't type in anything unexpected or (2) get user input more robustly. There are a number of good explanations about how to do option (2) here on Stack Overflow, and now that you know what the root cause of the issue is you can hopefully get the code fixed and working!
Use
std::cout << std::numeric_limits<int>::max() << std::endl;
and include #include <limits> and you will find out max int value on your machine.
int on your system is likely a 32-bit signed two's complement number, which means the max value it can represent is 2,147,483,647.
If you add bigger number stream will fail and all next read operations will return without reading anything.
Use unsigned long long which will allow you to insert bigger numbers.
You are taking your inputs as " int " and value range for int is between -2,147,483,648 to 2,147,483,647.
Which means that if you exceed this value 2,147,483,647 it can not be stored as an integer(int) type.
You should probably use Long data type for such large numbers.
You can add a following check in your code if the user input more than int limit
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input " << endl;
}
return a;
}
I would also add exit if invalid number
#include <iostream>
#include <cstdlib>
using namespace std;
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input " << endl;
std::exit(EXIT_FAILURE);
}
return a;
}
Note: You could also more info instead of just "Invalid input "
Output like size or limit info
enter 1 for addition and 2 for subtraction1
enter number4535245242
Invalid input
Program ended with exit code: 1

Strings and Ints in C++

First off, this is for a homework assignment, so I'd appreciate help and guidance rather than just the answer in code.
The purpose of the code should be for a user to input a number and a width.
If the width is longer than the number, the number will be printed out with zeros in front of the number. For example 43 3 would give 043.
If the width isn't longer just the number would be printed: 433 2 would be 433.
I think I have to get the count of characters in the number and compare it to the count of characters in the width (if-else statement).
Then, if the number of characters in the number is more, print out the number. Else, print out the width.
I think I get the number of zeros by subtracting the length of the number from the length of the width. Then use that to set the number of zeros. Like I said this is homework and would rather learn than be given the answer.
If anyone can help, it'll be appreciated.
#include <iostream>;
#include <string>;
using namespace std;
string format(int number, int width) {
int count = 0;
if (number > width)// This if-else is incomplete
return ;
else
}
int main()
{
cout << "Enter a number: ";
string n;
cin >> n;
cout << "Enter the number's width: ";
string w;
cin >> w;
format(n, w);
}
no need to checking string or other things write these code C++ will do it for you automatically.
#include <conio.h>
#include <iostream>
using std::cout;
using std::cin;
#include <string>;
using std::string;
#include <iomanip>
using std::setw;
void format(int number, int width)
{
cout.fill('0');
cout << setw(width) << number;
}
int main()
{
cout << "Enter a number: ";
int n;
cin >> n;
cout << "Enter the number's width: ";
int w;
cin >> w;
format(n, w);
_getch();
return 0;
}

c++ how to have a user input equation to be evaluated

My program is meant to ask a user to input an equation. Then find the maximum over an interval given by the user. When I compile my program, the output I get is:
Please complete the equation to be evaluated f(x)=
Please enter the first number of the interval to be checked:
Please enter the last number of the interval to be checked:
Please enter the desired initial step size:
sh: PAUSE: command not found
with the last line repeating many times.
I think the problem here has something to do with having the user input the equation to be tested. However, I'm unsure of how to fix this.
Here's my code
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int a, b, delta, fx, x, y;
int max = 0;
cout <<"Please complete the equation to be evaluated f(x)= " << endl;
cin >> fx;
cout <<"Please enter the first number of the interval to be checked: " << endl;
cin >> a;
cout << "Please enter the last number of the interval to be checked: " << endl;
cin >> b;
cout << "Please enter the desired initial step size: " << endl;
cin >> delta;
for(x = a; x <= b; x = x+delta)
{
y = fx;
if (y > max)
{
max = y;
cout <<"The maximum over the interval from " << a <<"to " << b <<"is " << delta;
}
else
{
delta= delta/2;
}
if (delta < pow( 10, -6))
{
system ("PAUSE");
}
}
return 0;
}
F(x) shouldn't be an integer variable, it should be a string variable. That way, the user can enter operators as characters instead of the compiler thinking they should be numbers. You would then have to process the string to determine the equation; this would require some thought, and possibly a more advanced data structure such as a binary tree.
Simply don't use system("pause"); in the if statement and you'll lose that error:
"sh: PAUSE: command not found". Place it right before the end of the main.
system("pause");
return 0;
As pointed out by others, the form of f(x) could be an issue with the above code.
Consider to redesign what to achieve for your program. One possibility is to narrow down the f(x) as polynomial function so that you can avoid parsing general algebraic equation, in this case you can ask:
how many degree of the polynomial ? upon this, it is followed by input the coefficient value for each factor in the polynomial equation.
This way, you can still use integer (or double - better) in the program.