Why does my C++ divide program not compile - c++

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

Related

Can I do in c++ something more than just 'x++', or 'x--'?

I made here a program to do 3x+1 math problem. So I am asking, if I could write in a c++ code something like x/2;, or x*3+1. These stuff what i put here are with mistakes. Then, is it possible in c++ to do that? If yes, how?
Here's the code:
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n"; int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x==1) {
if ((x%2)==0) {
x/2; cout << x << ", ";
} else if ((x%2)==1) {
x*3+1; cout << x << ", ";
}
}
return 0;
}
The output there was:
/tmp/GjudkYOaE4.o
Write an integer.
9
But I was waiting it to write the number 28, 14, and more, but it did nothing.
I can see that you are new to coding, I would suggest you to please read a good amount of information about if-elseif-else and while loop that you are using
I can show you a few corrections here
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n";
int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x!=1) { // x!=1 could be one of the terminating condition so when your x becomes 1, the loop would end. But of course the terminating condition depends on what you are trying to achieve
if (x % 2 == 0) {
x = x/2; //you need to assign the value back to x
cout << x << ", ";
} else { // you dont need else-if here because there could only be 2 possibilities for %2 operaion here
x = x*3+1;
cout << x << ", ";
}
}
return 0;
}
Give value to the same variable with assignment operator ('='):
x = x*3+1;
or
x = x/2;

Having trouble calling two variables from method into main 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;
}

Read a number, display it on the screen using a simple method (C++)

I am trying to read the n number using a method. When I try to build it with F7, the program returns an error:
Error 1 error C4700: uninitialized local variable 'n' used.
Could you please help me create a method to read a number and display it on the screen?
#include <stdafx.h>
#include <iostream>
using namespace std;
void read_number(int n){
do {
cin >> n;
} while (n < 3 || n > 50);
}
int main(){
int n;
read_number(n);
cout << "Number: " << n << endl;
return 0;
}
You're passing the value of main's variable n to the function.
The variable is not modified by the function, only the function's parameter is.
The simplest way is to return a value from the function:
int read_number(){
int x = 0;
do {
cin >> x;
} while (x < 3 || x > 50);
return x;
}
int main(){
int n = read_number();
cout << "Number: " << n << endl;
return 0;
}
or, if you definitely want to modify main's variable, pass a reference to it:
void read_number(int& x){
do {
cin >> x;
} while (x < 3 || x > 50);
}
int main(){
int n;
read_number(n);
cout << "Number: " << n << endl;
return 0;
}
void read_number(int n) {
In this function n is passed by value, which means that any modification that you made on n inside the function's body is not reflected outside the function.
If you want to return the read number to the caller, either return it from the function, making it:
int read_number()
or pass pass n by non-const reference:
void read_number(int& n);
I'd prefer the former.
C++ is pass by value unless you specify otherwise.
With that in mind, note that a copy is passed to readNumber; it doesn't mutate its argument.
Change the helper to:
void read_number(){
int n;
do {
cin >> n;
} while (n < 3 || n > 50);
return n;
}
Note we're mutating the local variable instead, then returning it.
Then, change your main to deal with the change:
int main(){
int n = read_number();
cout << "Number: " << n << endl;
return 0;
}
As #Mr.C64 points out, you can pass by reference instead, and then you can mutate the parameter, but that should be avoided unless it's absolutely necessary. It's much harder to read code containing mutations like that.

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

Can't fix errors in monte carlo program

I'm trying to write a program that simulates darts being thrown at a standard curve. Whenever I get close to debugging the entire thing something else pops up. So far I am getting a lot of errors like:
Error: variable is not declared in this scope
Also there's an error I have no idea how to fix which has to do with C++ comparing pointers and integers
I'm pretty new to C++ so any pointers would be greatly appreciated.
Here's what I got so far.
note: errors are on lines 67, 70, 72, and 75.
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
double seed(int darts, int x);
int main ()
{
int darts, x_max;
double area;
char again = 'y';
char giveDarts;
while (again == 'y' || again == 'Y');
cout << "Run program (y/n)?";
cin >> giveDarts;
switch (giveDarts) {
case 'y':
case 'Y':
cout << "Enter the ammount of darts to be thrown: "; //since we are simulating DARTS I will use the varible darts instead of "NumberOfSamples"
cin >> darts;
srand(darts);
default:
break;
}
cout << "Enter maximum value of x: ";
cin >> x_max;
while (x_max < 0);
cout << "Please enter a positive value of x: ";
cin >> x_max;
cout << endl;
srand(time(NULL));
area = seed(darts, x_max);
cout << "Estimate of area under curve is: " << area << endl;
cout << "Go again? ";
cin >> again;
return 0;
}
double seed(int darts, int x_max)
{
int i, num_darts=0; //num_darts instead of SamplesInsideArea.
double area;
for(i=1; i<=darts; i++) // for loop
{
double x, y;
double pi = 3.14;
double n (double t);
return 1/sqrt(2*pi)*exp(-pow(t,2)/2); //error:'t' was not declared in this scope
x = rand() / static_cast<double>(RAND_MAX);
y = rand() / static_cast<double>(RAND_MAX);
n(0) = (x*x_max + y*y_max); //error: y_max was not declared in this scope
if(num_darts <= n) //error: ISO C++ forbids comparison between pointer and integer
num_darts++;
area*n(0)+0.5 = static_cast<double>(num_darts)/darts; //error: invalid Ivalue in assignment.
}
return area;
}
This line:
double n (double t);
is prototyping a function n that takes one parameter double t. This is causing two of the errors:
error: 't' was not declared in this scope (because function prototypes don't declare variables)
error: ISO C++ forbids comparison between pointer and integer (because n is a pointer to a function)
Did you mean this to be a function prototype? If not, what did you mean?
The error error: y_max was not declared in this scope is straight-forward. y_max isn't declared anywhere.
This line:
area*n(0)+0.5 = static_cast<double>(num_darts)/darts; //error: invalid Ivalue in assignment.
The error error: invalid Ivalue in assignment is because you can't assign a value to an expression. What did you intend to do here?
Additionally, there are some other problems:
This line:
while (again == 'y' || again == 'Y');
will cause your program to go into an infinite loop, since you set again = 'y' just before it, and the semicolon tells the compiler this:
while (again == 'y' || again == 'Y')
{
// do nothing
}
To fix this, remove the semicolon and put braces around the code that needs to be inside the while loop. The same issue exists later too (while (x_max < 0);).
Someone else pointed out this one:
return 1/sqrt(2*pi)*exp(-pow(t,2)/2);
which occurs in the middle of the function. This will cause that function to finish immediately and return the calculated value. Is this what you intended? The code after this line will never run.
More problems:
This code doesn't handle the N/n case. The program will not stop when you type 'n', and will probably crash.
switch (giveDarts) {
case 'y':
case 'Y':
cout << "Enter the ammount of darts to be thrown: "; //since we are simulating DARTS I will use the varible darts instead of "NumberOfSamples"
cin >> darts;
srand(darts);
default:
break;
}
cout << "Enter maximum value of x: ";
Use braces to control loops, not whitespace. Instead of this:
while (x_max < 0);
cout << "Please enter a positive value of x: ";
cin >> x_max;
cout << endl;
You want this:
while (x_max < 0)
{
cout << "Please enter a positive value of x: ";
cin >> x_max;
cout << endl;
}
This line:
area*n(0)+0.5 = static_cast<double>(num_darts)/darts;
If you're trying to set area, this needs to be in the form:
area = static_cast<double>(num_darts)/darts; // n(0)+0.5 goes where??
When you are first learning to program C++, I suggest that you declare and define all of your functions at the global level. This means that lines like double n (double t); should never appear inside any braces. So to fix part of the problem with your code, move these two lines of code:
double n (double t);
return 1/sqrt(2*pi)*exp(-pow(t,2)/2);
outside of the seed() function and make a few minor modifications so it looks like this:
double n (double t) {
return 1/sqrt(2*pi)*exp(-pow(t,2)/2)
}
This should help you in the right direction. (Just be sure that pi is declared either as a global constant.)