Having trouble calling two variables from method into main C++ - c++

I am having trouble with a very simple program. I need to call in a method (getNumber) outside of main that takes two numbers from the user and then store those numbers. Those two numbers are then used in a calculation method (math) which is also called into main. I am getting an uninitialized local variable for my two numbers I am calling in from getNumber. I would like the user to enter two numbers have them added together and display the result but by calling in methods.
#include <iostream>
#include <string>
using namespace std;
int getNumber(int x, int y)
{
// here is where the user is prompted to input two numbers
cout << "Please enter two values" << endl;
cin >> x >> y;
return x, y;
}
int math(int x , int y) // here is where the calculations are done
{
int result;
result = x + y;
return result;
}
int main()
{
int x;
int y;
int result;
x = getNumber(x, y); // trying to call in the input method here
result=math(x,y); // calling in claculation method
cout << result;
system("pause");
return 0;
}

void getNumber(int &x, int &y)
{
cout << "Please enter two values" << endl;
cin >> x >> y;
}

Related

write a complete program that will read 3 NUMBers from user and calculates and displays the product only of the positive integers

This is what I've tried so far
// Calculate the product of three integers
#include <iostream> // allows program to perform input and output
using namespace std;
// function main begins program execution
int main()
{
int x; // first integer to multiply
int y; // second integer to multiply
int z; // third integer to multiply
int result; // the product of the three integers
cout << "Enter three integers: "; // prompt user for data
cin >> x >> y >> z;
result = x * y * z;
}
what can i do to solve this question?
EDIT:
If you do not need it to loop use a if instead of a while.
Looks like you need to study some conditional statements try:
result = x*y*z;
while(result < 0){
cout << "Enter three integers: "; // prompt user for data
cin >> x >> y >> z;
}
cout << result << endl;
Should work fine...
I would suggest using a condition to check the number at the input itself:
#include <iostream>
int main() {
int inum1 = 0;
std::cin >> inum1;
if (inum1 < 0) { inum1 = 1; }
int inum2 = 0;
std::cin >> inum2;
if (inum2 < 0) { inum2 = 1; }
int inum3 = 0;
std::cin >> inum3;
if (inum3 < 0) { inum3 = 1; }
std::cout << inum1*inum2*inum3 << "\n";
return 0;
}
Notice that in my example I have used std::cout and std::cin instead of using namespace std
use of using namespace std is fine if you're a beginner or the program is small, but is discouraged for large programs :)
If you find typing std:: tedious, you can instead include the following statements:
using std::cin;
using std::cout;
Also, printf and scanf is usually preferred over cin and cout for fast I/O.

C++ Calling - search function

I was wondering how I could finish up this program. It's to perform a linear search on a list "ll" (which length is 31) for the user inputted item it, returning the user inputted numbers and their locations if they're found.
Problem: I'm not sure how to call the functions in this specific scenario, I don't really need to use pointers or pass a value, so the lack of these actually makes it more confusing for me, as those are fairly common scenarios.
#include <iostream> //enables usage of cin and cout
#include <cstring>
using namespace std;
int search (int i, int it, int ll, int z);
int printit (int i, int it, int ll, int z);
int main ()
{
int i,it,z;
int ll[] = {2,3,4,5,6,2,3,44,5,3,5,3,4,7,8,99,6,5,7,56,5,66,44,34,23,11,32,54,664,432,111}; //array hardwired with numbers
//call to search
return 0;
}
int search (int i, int it, int ll, int z)
{
cout << "Enter the item you want to find: "; //user query
cin >> it; //"scan"
for(i=0;i<31;i++) //search
{
if(it==ll[i])
{
//call to printit
}
}
return 0;
}
int printit (int i, int it, int ll, int z)
{
cout << "Item is found at location " << i+1 << endl;
return 0;
}
There is a problem with each of the parameters to search:
i's passed value gets overwritten before it gets used, and thus should be a local variable
Same thing for it
ll should be an array of ints
z isn't used at all
Things are even worse for printit: 3 of the 4 parameters are ignored.
Search and print don't need to return int, if you have already print out the results. Also some declared variables are useless. The following code would work:
#include <iostream> //enables usage of cin and cout
#include <cstring>
using namespace std;
void search (int ll[]);
void printit (int n);
int main ()
{
// int i,it,z;
int ll[] = {2,3,4,5,6,2,3,44,5,3,5,3,4,7,8,99,6,5,7,56,5,66,44,34,23,11,32,54,664,432,111}; //array hardwired with numbers
//call to search
search(ll);
return 0;
}
void search (int ll[])
{
cout << "Enter the item you want to find: "; //user query
cin >> it; //"scan"
for(i=0;i<31;i++) //search
{
if(it==ll[i])
{
//call to printit
printit(i);
}
}
// return 0;
}
void printit (int n)
{
cout << "Item is found at location " << n+1 << endl;
// return 0;
}

C++ object oriented problems [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This is an assignment i am trying to figure out:
Create a new project named Project3 and create a class named Rover
Within the Rover class, specify the following member instance variables:
name(string)
x position on a grid (integer)
y position on a grid (integer)
direction by compass – N, S, E, or W (String)
speed (0 – 5 meters per second, integer)
Within the Rover class, specify the following methods:
Default constructor – set the rover’s position to (0,0), its speed to 0, its direction to
North.
Constructor that receives parameters to initialize all five instance variables described above
Setter methods for each instance variable
Getter methods for each instance variable
getRoverData – returns a string that displays values for each instance variable of the
current rover object, placing each value on a separate line, as follows:
Rover name: A
X-position: 0
Y-position: 0
Direction: E
Speed: 1
Create a class client (main) that creates an array of the a maximum of five rovers and gets the initial
values for all rovers from the user. After the user specifies values for each rover, display a summary
of the rover’s values as shown above.
I have about a billion errors and i dont know why.
using namespace std;
class Rover {
private:
string name;
int x;
int y;
string direction;
int speed;
int position[10][10];
public:
void Rover();
void constructor(string name, int x, int y, string direction, int speed);
void setName(string name);
void setX(int x);
void setY(int y);
void setDirection(string direction);
void setSpeed();
string getName();
int getX();
int getY();
string getDirection();
int getSpeed();
string getRoverData();
};
void Rover::Rover() {
r1.position[0][0];
r1.speed = 0;
r1.direction = "N";
}
string Rover::getRoverData() {
cout << "Rover name: " << r1.getName() << endl;
cout << "X-position: " << r1.getX() << endl;
cout << "Y-position: " << r1.getY() << endl;
cout << "Direction: " << r1.getDirection() << endl;
cout << "Speed: " << r1.getSpeed() << endl;
}
void Rover::constructor(string name1, int x1, int y1, string direction1, int speed1) {
r1.name = name1;
r1.x = x1;
r1.y = y1;
r1.direction = direction1;
r1.speed = speed1;
}
void Rover::setName(string name) {
r1.name = name;
}
void Rover::setX(int x) {
r1.x = x;
}
void Rover::setY(int y) {
r1.y = y;
}
void Rover::setDirection(string direction) {
r1.direction = direction;
}
void Rover::setSpeed(int speed) {
r1.speed = speed;
}
string Rover::getName() {
return name;
}
int Rover::getX() {
return x;
}
int Rover::getY() {
return y;
}
string Rover::getDirection() {
return direction;
}
int Rover::getSpeed() {
return speed;
}
int main(int argc, char** argv) {
string name;
int x;
int y;
string direction;
int speed;
Rover r1;
r1.constructor("Yoda", 3, 3, "N", 3);
cout << "Enter name for Rover: ";
cin >> name;
r1.setName(name);
cout << "Enter its x position: ";
cin >> x;
r1.setX(x);
cout << "Enter its y position: ";
cin >> y;
r1.setY(y);
cout << "Enter direction N,E,S,W: ";
cin >> direction;
r1.setDirection(direction);
cout << "Enter its speed: ";
cin >> speed;
r1.setSpeed(speed);
r1.getRoverData();
return 0;
}
Your example appears incomplete. I'm guessing you just missed including the following lines in your post
#include <string>
#include <iostream>
using namespace std;
First, constructors do not have a return type so void Rover(); makes no sense. Remove void and you're golden there.
Second, what exactly do you think r1 is supposed to be? The compiler should tell you the identifier is undefined because it isn't. remove r1. from your member functions (i.e. anything function starting with Rover::. and you're golden there.
Third, what do you think r1.position[0][0] is going to do? It's just an expression that does nothing. Even position[0][0] is not going to do anything. Perhaps you want to initialize the array somehow but you haven't provided enough information to determine what you're trying to accomplish with it.
Fourth, the member function void Rover::setSpeed(int) has not been declared within the Rover class. Did you forget something? Based on your code it should be
int Rover::getSpeed()
{
return speed;
}
Fifth, void Rover::setSpeed(); doesn't make much sense unless it actually accepts an argument.

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
}
.

Why does my C++ divide program not compile

I tried to make a program that has a correct Divide function.
My code was:
#include <iostream>
using namespace std;
double x,y,z,a;
double divide(x,y) {
if (x >= y) {
x=z;
z=y;
y=x;
return(x/y);
}
else
return(y/x);
}
int main()
{
double x,y,z ;
cout << "Enter x " <<endl;
cin >> x;
cout << "Enter y " <<endl;
cin >> y;
a = divide (x,y);
cout << a <<endl;
system("pause");
return 0;
}
And I have 2 errors:
expected `,' or `;' before '{' token
on the { line. Right under the double divide (x, y) line
And another error
divide cannot be used as a function
on the a = divide (x, y); line.
I am using Code: Blocks
You need to specify a proper function signature for the function divide. Specifically, the arguments to the function are missing their types:
double divide(double x, double y)
{
...
}
You also need to create a scope for each block in an if statement:
if (x > y)
{
...
}
else
{
...
}
The braces in an if statement don't go around the else block. You need a separate pair of braces there. Try:
if (x >= y){
x=z ;
z=y ;
y=x ;
return(x/y);
}
else {
return(y/x);
}
The second set of braces (around the one line of the code after the 'else' aren't strictly necessary; you can leave the braces off an if or an else if the block is only one line long. But while you're new you probably shouldn't, as it's easy to make mistakes that way.
Also, you have not provided types for the x and y variables in your divide function. You must specify types for them, just as you would for any other variable. You've written
double x,y,z,a ;
...outside of the function, but that doesn't help; it defines new double variables named x, y, z,and a, completely independent of the ones in your function.
Corrected your braces in your if...else. also need to define a type in your function's parameters.
using namespace std;
double x,y,z,a ;
double divide (double x, double y)
{
if (x >= y){
x=z ;
z=y ;
y=x ;
return(x/y);
}
else
{
return(y/x);
}
}
int main()
{
double x,y,z ;
cout << "Enter x " <<endl;
cin >> x ;
cout << "Enter y " <<endl;
cin >> y ;
a = divide (x,y);
cout << a <<endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
// divides x/y
double divide (x,y)
{
if(y != 0)
{
/*{} <- this is called a scope.
it is important to keep track of scopes.
each function has it's own scope
each loop or an if instruction can have it's own scope
in case it does - all the instructions from the scope will be executed
in case it doesn't - only the 1st instruction after the if/else/for/while etc. will be executed
Here's another funny thing about scopes :
{
double x; // this variable exists ONLY within this scope
}
{
// y doesn't exist here
{
double y; // y exists here. it's local
}
// y doesn't exist here
}
*/
return x / y;
}
else
return 0;
}
int main()
{
double x,y;
cout << "Enter x " <<endl;
cin >> x ;
cout << "Enter y " <<endl;
cin >> y ;
double a = divide (x,y);
cout << a <<endl;
cin;
return 0;
}