C++ bug uninitialized variable - c++

I am instructed to write a program where the user inputs two values, can be with decimals. Then create a void function that changes the precision to 4 digits. I created a program and it runs the first value (x) just fine but for some reason, it's giving me an error saying the second variable is uninitialized (h) any advice would be appreciated! I think that I've been looking at it for too long and just can't spot it!
Below is the code:
#include <iostream>
#include<cmath>
using namespace std;
void display_it(double x, double h);
int main(void) // getting input from user and displaying output
{
double x, h;
cout << "Please enter 2 values to be displayed with precision.\n";
cin >> x, h;
cout << x << endl;
cout << h << endl;
return 0;
}
void display_it(double x,double h) //does the precision change of x and h
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(4);
}

This line:
cin >> x, h;
is not reading in 2 values from cin. It's actually only reading in 1 value, after which the expression h that's after the , is evaluated (which does nothing). So the warning/error about h being uninitialized is correct.
The correct way to read 2 values is:
cin >> x >> h;

Related

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

setprecision() not working as expected

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.

The program does'nt give output

I am using the following code to print out the code, and i doesn't show the correct area of the circle. it shows -215487854145 as the area of the circle..
please help me
the code below code:
kindly help me as i am new to this language, i think i did everything right please
#include <iostream>
using namespace std;
int main()
{
int a, r;
a = 3.14 * r * r ;
cout << "enter Radius";
cin >> r;
cout << "area of circle is";
cout << a;
return 0;
}
Two issues.
You are computing a using an unitialised value of r. The program behaviour is undefined. Move it after the cin >> r; statement.
Working in int could cause you issues with overflow. The largest possible value of an int in C++ can be as small as 32767. Use a double instead, and an improved value of PI. Note that the type of 3.14 * r * r is a double anyway, and you're currently forcing a conversion to int.
As for PI itself, it is not included in the C++ standard library. Consider
constexpr double pi = 3.14159265358979323846264338328;
or take one from a mathematics library if you're using one.
You used r in a calculation before you ever read in the value. Move it after you read it in.
cin >> r;
a = 3.14 * r * r ;
Unlike in mathematics,
a = 3.14 * r * r ;
does not define a relationship between a and r (it's not an equation).
Instead, it means "replace the current value of a with 3.14 times the square of the current value of r".
Since you haven't given r a value yet, the result is undefined.
You need to move the lines around a bit in order to not use values that don't exist yet.
You should also not use integers for this, but floating-point.
double r;
cout << "enter Radius";
cin >> r;
double a = 3.14 * r * r ;
cout << "area of circle is " << a;
#include <iostream>
using namespace std;
int main()
{
int a, r;
// your r was not initialized when you use it.
a = 3.14 * r * r ;
cout << "enter Radius";
cin >> r;
cout << "area of circle is";
cout << a;
return 0;
}
right answer:
#include <iostream>
using namespace std;
int main()
{
int a, r;
cout << "enter Radius";
cin >> r;
//after r being initialized.
a = 3.14 * r * r;
cout << "area of circle is";
cout << a;
return 0;
}

Really need some assistance, first programming project

My formatting is really bad, and I'm sorry for that, but I'm still in the very early stages of learning C++. Anyway, no matter what I try, I always get an expected unqualified ID error on line 51. Any assistance would be greatly appreciated! And no, the code is not finished, its due March 20th, just wanted to start on it early. And this is NOT how I wanted to format it, but this is how it was stated on the rubric. I'm brand new to functions, so yeah, any help would be awesome!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int menu (int); //Menu prototype for 4 options
int main()
{
const int numWidth = 4;
int choice, pick;
cout << "Welcome! Please select your choice by entering 1, 2, 3, or 4!" << endl;
cout << "1:";
cout << right << setw(numWidth) << " Enter the Grades" << endl;
cout << "2:";
cout << right << setw(numWidth) << " Display the Grades" << endl;
cout << "3:";
cout << right << setw(numWidth) << " Show overall Grade" << endl;
cout << "4:";
cout << right << setw(numWidth) << " Exit the program" << endl;
cout << "Select your choice and press enter ";
cin >> choice;
pick = menu(choice);
cout << pick;
if (choice ==1)
{
cout << ". Please enter your grades.\n";
}
float AssignmentGrade(float, float, float, float); // Assignment Grade Prototype
{
float asgnment1, asgnment2, asgnment3, asgnment4, total;
cout << "First, enter your 4 assignment grades ";
cin >> asgnment1 >> asgnment2 >> asgnment3 >> asgnment4;
total = AssignmentGrade (asgnment1, asgnment2, asgnment3, asgnment4);
cout << total;
return 0;
}
}
float AssignmentGrade (float num1, float num2, float num3, float num4)
{
float asgnmentgrade;
asgnmentgrade = num1*0.05 + num2*0.05 + num3*0.05 + num4*0.05;
cout << "Total points, including weights, for assignment grade is ";
return asgnmentgrade;
}
float LabTestGrade (float, float, float); // Right here, line 51, is where I get expected unqualified ID error before {
{
float lab1, lab2, lab3, total;
cout <<"Next, please enter your 3 lab test scores!";
cin >> lab1 >> lab2 >> lab3;
total = LabTestGrade (lab1, lab2, lab3);
cout << total;
return 0;
}
float LabTestGrade (float lab1, float lab2, float lab3)
{
float LabGrade;
LabGrade = lab1*0.10 + lab2*0.10 + lab3*0.10;
cout << "Total points earned from lab tests is";
return LabGrade;
}
int menu (int num)
{
int option;
option = num;
cout <<"You have selected ";
return option;
}
Delete unnecessary ; in your 51st line: float LabTestGrade (float, float, float);
Dont forget that ; is used for the end of a command. If you define a function, you don't use it. Look at th following model:
float function (float parameter) {
command();
command();
return 0;
}
Edit: There's the same syntax error in your 31th line.
Delete ; again in float AssignmentGrade(float, float, float, float);
You will find yourself running into a few other problems with this function, apart from the original unqualified ID that #Nichar answered.
At Line 50 you have:
float LabTestGrade (float, float, float) { // Function Code }
and at Line 60 you have:
float LabTestGrade (float lab1, float lab2, float lab3) { // Function Code }
This will cause a compile error as you are trying to define another function with the exact same name and parameters. (Redefinition error)
Although these functions may look slightly different as you have named the parameters of the second one (float lab1, float lab2, float lab3), to the compiler it will simply see two functions that are named the same and take in the same types as parameters.
That being said, you can delete the parameters in the first LabTestGrade() as they aren't actually being used inside its function.
float LabTestGrade() { // Function Code }
Finally, you are also going to want to swap around the order that these two functions are being defined. I suggest googling C++ Scope but basically the first LabTestGrade() is making a call to the second LabTestGrade(float lab1, lab2, lab3) like so.
total = LabTestGrade(lab1,lab2,lab3);
However, the second LabTestGrade hasn't been defined yet within your program so it will try to call the first LabTestGrade() again and give you an error because the first LabTestGrade() doesn't take in any parameters now and this line of code is trying to pass into it three floats into a function that takes in nothing.
Alternatively, you could just declare the functions above your main function like you had done for your menu function.
float LabTestGrade();
float LabTestGrade(float lab1, float lab2, float lab3);
int menu(int) // Menu prototype for 4 options
Hi even im a beginner but heres what i think -
First of all
The menu prototype in the beginning is incorrect . Prototypes should be exactly same as the function itself .
Correct prototype will be
int menu (int num);
In line 51 , in the parameter bracket, try writing the full name of the float types you r trying to get. Also remove the semicolon. Ex:-
float LabTestGrade (float a , float b , float c) { }
A similar mistake is made in the AssignmentGrade function which takes 4 floats.
Try writing the full name as parameters. Remove the semi colon.
Write the function prototypes separately in the beginning outside the main.
You have to create a separate prototype for every function you make and remember - prototypes should have the same name as the function. Just you need to replace the curly braces with a semi colon.
Hope this helps.
EDIT:- You can also try writing the functions outside main and then use prototypes in the beginning outside the main.

Comparing smallest user input for C++

I tried to find the smallest number within 3 inputs. Here is my codes :
int main ()
{
double x = 4.0;
double y = 5.0;
double z = 3.0;
smallest(x,y,z);
cout << smallest << endl;
system("PAUSE");
}
double smallest(double x, double y, double z)
{
double smallest;
if ((x < y)||(x< z)) {
smallest = x;
} else if ((y < z)||(y < x)) {
smallest = y;
} else {
smallest = z;
}
return smallest;
}
However, I keep getting error. It stated that my smallest method in main method with undeclared identifier. This works when using eclipse but not visual studio. Can somebody explain to me why?
Thanks in advance.
Updated portion.
So I tried to do validation for this program. I want to ensure users only enter number and here are my codes :
double x, y, z;
bool correct_input = false;
do{
cout << "Enter first integer : " ;
cin >> x;
if(isdigit(x)){
correct_input = true;
}
}while(!correct_input);
do{
cout << "Enter second integer : ";
cin >> y;
if(isdigit(y)){
correct_input = true;
}
}while(!correct_input);
do{
cout << "Enter third integer : ";
cin >> z;
if(isdigit(z)){
correct_input = true;
}
}while(!correct_input);
cout << "Smallest integer is : " << smallest(x,y,z) << endl;
system("PAUSE");
When I entered alphabet or whatever except numbers, I get debug assertion failed. It does not prompt until user enter correct input. Can somebody help?
First of all, if you wish to use smallest() before it's defined, you need to prototype it. Add the following before main():
double smallest(double x, double y, double z);
Also, you are ignoring the return value of smallest(). Change
smallest(x,y,z);
cout << smallest << endl;
to
double smallest_val = smallest(x,y,z);
cout << smallest_val << endl;
This isn't the question you asked but your function is bugged because you confused || and &&.
Your function should be
double smallest(double x, double y, double z)
{
double smallest;
if (x < y && x < z)
smallest = x;
else if (y < z && y < x)
smallest = y;
else
smallest = z;
return smallest;
}
x is the smallest number if it is less y and it is less than z.
update
First thing to say is that if you want integers then you should be using int not double.
Second thing, isdigit doesn't do what you think it does. You've actually set yourself a very difficult problem. Here's one way to do it
#include <string> // for string class
bool correct_input = false;
do
{
cout << "Enter first integer : " ;
if (cin >> x)
{
correct_input = true;
}
else
{
// cin is in a error state after a failed read so clear it
cin.clear();
// ignore any remaining input to the end of the line
string garbage;
getline(cin, garbage);
}
}
while(!correct_input);
But this doesn't work perfectly. For instance if you enter abc then your program will ask for more input, but if you enter 123abc, then you will get the integer 123 even though 123abc is not a valid number.
If you really want to do this properly (and it is hard) then you must read in a string, check if the string could be converted to a number, if it can then do the conversion, if it can't then ask for more input.
Put this line above your main ;).
double smallest(double x, double y, double z);
You need to declare any function you make. This is called making a function header.
You should declare you function so that the compiler can recognize it.
Put its prototype above main function as this:
double smallest(double, double, double);
int main()
{
//Staff
}
There are two problem, here, one related to how to get the smallest, and the other related to ho get correct input.
For the first problem, let me propose a recursive approach:
// this is trivial
double smallest(double x, double y)
{ return (x<y)? x: y; }
// the smalles of three is the smallest between the smallest of two and the third
double smallest(double x, double y, double z)
{ return smallest(smallest(x,y),z); }
For the second problem, you have the same problem for each of the variables, so let's make a function for it:
#include <iostream>
#include <limits>
#include <string>
double read(std::istream& s, std::ostream& o, const std::string& message)
{
for(;;) //stay here until kiked out
{
double d=0.; //just a safe value - no particular meaning
o << message << std::endl; // prompt the request
bool good(s >> d); //read a double and keep the state
if(!good) s.clear(); //if we failed to read, clean the stream state
//in any case, discard everything unread until the return.
s.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if(good) return d; //if reading succeeded, return.
//overwise loop back
}
}
This is based on the fact the std::cin have a state that is set to "bad" is the input cannot be read in the given variable.
We just read, and, if it fails, redo again and again.
But fist we have to clear the state, so thet the input can be unlocked.
Independently og good an bad reading, we have then to discard everuthing "extra" that can be typed in the line (think to 123asdf: we successfully read 123, but we have to discard abc)
The the reading was successful we just return it, otherwise we loop over and over until we get it.
The program itself, at this point will reduce to:
int main()
{
double x = read(std::cin, std::cout, "Enter first value");
double y = read(std::cin, std::cout, "Enter second value");
double z = read(std::cin, std::cout, "Enter third value");
std::cout << "the smallest numer is: " << smallest(x,y,z) << std::endl;
return 0;
}
that can run this way:
Enter first value
7
Enter second value
5.2yyyy
Enter third value
sf3
Enter third value
455
the smallest numer is: 5.2
A more advanced technique can be transform the function into a manipulator class, like this:
class read_value
{
public:
read_value(double& d, const std::string& prompt_, std::ostream& out_ = std::cout)
:z(d), prompt(prompt_), outstream(out_)
{}
friend std::istream& operator>>(std::istream& s, const read_value& a)
{
for(;;)
{
a.outstream << a.prompt << std::endl; // prompt the request
bool good(s >> a.z); //read a double and keep the state
if(!good) s.clear(); //if we failed to read, cleanr the stream state
//in any case, discard everything unread until the return.
s.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if(good) return s; //if reading succeeded, return.
//overwise loop back
}
}
private:
double& z;
std::string prompt;
std::ostream& outstream;
};
letting the program a more idiomatic form:
int main()
{
double x,y,z;
std::cin >>
read_value(x,"Enter first value") >>
read_value(y,"Enter second value") >>
read_value(z,"Enter third value");
std::cout << "the smallest numer is: " << smallest(x,y,z) << std::endl;
return 0;
}
Another point can be the fact the user can loop forever by never typing a good sequence.
We can fix a maximum attempt limit introducing a counter in the for loop, and setting the input to "failed" if the loop terminates without returning:
friend std::istream& operator>>(std::istream& s, const read_value& a)
{
for(int i=0; i<10; ++i)
{
... //same as before
}
return s; //s will be returned in failed state
}
And then checking in the main program:
int main()
{
double x,y,z;
std::cin >>
read_value(x,"Enter first value") >>
read_value(y,"Enter second value") >>
read_value(z,"Enter third value");
if(!std::cin)
{
std::cout << "bad input." << std::endl;
return -1; //report as "program failed"
}
std::cout << "the smallest numer is: " << smallest(x,y,z) << std::endl;
return 0; //succeeded
}
.