Variables not declared in scope error/too few arguments to function - c++

I am writing a simple code to take a number and a power based off user input and square the number to that power using functions. While attempting to compile the code, though, I get multiple errors. here is the code:
#include <iostream>
using namespace std;
double power(double& n1, sq)
{
for (int i = 0; i < sq; i++) {
n1* n1;
}
return n1;
}
int main()
{
double power(double&);
double num1, square;
cout << "Enter a number IMMEDIATLY: ";
cin >> num1;
cout << "\nEnter a power: ";
cin >> square;
power();
cout << num1 << endl;
return 0;
}
Here are the errors that I am receiving:
||=== Build: Debug in practice (compiler: GNU GCC Compiler) ===|
|5|error: 'sq' has not been declared|
In function 'double power(double&, int)':|
|6|error: 'sq' was not declared in this scope|
|7|warning: statement has no effect [-Wunused-value]|
In function 'int main()':|
|22|error: too few arguments to function 'double power(double&)'|
|15|note: declared here|
|17|warning: unused variable 'ans' [-Wunused-variable]|
||=== Build failed: 3 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|
Any help or light shed on how to fix these errors would be much appreciated, for i have been stumped for quite sometime. Thank you!
edit: so I have parsed square as an int and initialized the variables into the power() (as you guys have said) but now the code produces the incorrect answer as the output (anything bigger than squaring the number produces incorrect output).
#include <iostream>
using namespace std;
double power(double& n1, int& sq) {
for (int i=2; i<=sq; i++) {
n1*=n1;
}
return n1;
}
int main()
{
double power(double& n1, int& sq);
double num1;
int square;
cout << "Enter a number IMMEDIATLY: ";
cin >> num1;
cout << "\nEnter a power: ";
cin >> square;
power(num1, square);
cout << num1 << endl;
return 0;
}

To answer your second question, simply trace through the code with an example:
Let's say the inputs are
n1 = 3
sq = 3
We know that 3^3 = 27, so lets see if we get that answer.
First, the operation n1 *= n1 is multiplying n1 by itself. For squaring alone, this is fine: 3*3 = 9. But then you loop through it again, and n1 is now 9, so the code will compute 9*9 = 81.
See if you can figure it out from here. Hint: you'll need another variable for storage.
Also, your return statement is outside of your brackets for the power() function. Though its working on its own because you passed &n1 in as a reference. Either remove the return statement altogether, or make a new variable in main that receives the value from power(). If you do the latter, remove the & symbol and place the return statement within the power brackets. To get a better understanding of passing by reference vs. passing by value, see this link. Good luck!

Related

Creating a simple crackme program in C++ problems with variable and input

So I am trying to learn C++ so I can learn some reverse engineering that why I am trying to create this simple crack me program to get a foundation going and not take someone else's project as I choose my own path. However I am using CodeBlocks as the other IDEs were not being cooperative and am enjoying it and has given me some error and two lines. Below is the following code. So there errors are the following:
||=== Build: Debug in SimpleProgram (compiler: GNU GCC Compiler) ===|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp||In member function 'int checker::processing(int)':|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp|15|warning: no return statement in function returning non-void [-Wreturn-type]|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp||In function 'int main()':|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp|22|error: 'x' was not declared in this scope|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
#include <iostream>
using namespace std;
class checker{
public:
int number;
processing(int x){
x = number;
if ( number == 10 ){
cout << "Well done!";
} else {
cout << "Keep trying!";
}
}
};
int main()
{
checker cracking;
cout << "Please enter in the correct number";
cin >> cracking.processing(x);
return 0;
}
Image of the project and error
A function always has a return type, even if your not attempting to return anything it will have the void signature. If your intent was to take input of a number passed from main and display it via a function in your class checker through an object of the same, this is how it would look like:
#include <iostream>
using namespace std;
class checker{
public:
int number;
void processing(int x)
{
if (x==10)
cout << "Well done!";
else
cout << "Keep trying!";
}
};
int main()
{
checker cracking;
cout << "Please enter in the correct number \n";
int n;
cin >> n;
cracking.processing(n);
return 0;
}
I've cleaned the code up and included comments that serve as notes:
#include <iostream>
using namespace std;
class checker{
public:
void setnumber(int i){ //it's a good habit to put variables in private and access them with a public function
this->number = i;
};
int processing(int x){ //x is just a placeholder value for whatever you put in here. You can't use it in the rest of the program
if ( x == 10 ){
cout << "Well done!" << endl;
return 1; //this condition indicates success
} else {
cout << "Keep trying!" << endl; //the endline just makes it so you aren't typing on the same line as the message
return 0; //this condition indicates success hasn't been reached yet
}
}
private:
int number;
};
int main()
{
checker cracking;
cracking.setnumber(10); //the number is set to 10
int i, l; //i is the guess number, l is a condition for the loop
cout << "Please enter in the correct number" << endl;
do{ //this loop sets it up so that you can have multiple tries
cin >> i;
l = cracking.processing(i);
}while(l!=1); //and this condition (the return value of processing(), breaks the loop on success
return 0;
}
The main issue that popped out at me was the use of x.
Trying to set x to number. In functions, the parameters are just placeholder values for arguments that will be passed into later. Then later on when you tried to use x as an input in the main() program. You were calling that function (using it) and needed an int as input.
Don't worry. It's confusing in the beginning for everyone (although to be fair, as you progress you'll just find new things to be confused about. It never really stops). Keep at it and it'll all make sense in time.

2 errors on my simple block of code in a C++ file. error C2059: syntax error : '?'. 2nd IntelliSense: expected an expression. What is wrong?

#include <iostream>
#include <string>
using namespace std;
int main() {
int passes; //The number of passed classes
int fails; // The number of failed classes
double grade; //The current grade to be analyzed
//Initialize number of passes and fails
passes = 0;
fails = 0;
//Prompt for first grade
cout <<?Please enter a numeric grade(> 0) : ? :
cin >> grade;
return 0;
}
I'm not 100% sure what you've tried to achieve in the cout line, it looks pretty odd. Anyways, try to wrap the string you wish to print with quotes ("). After the cout, you should supply some parameters to the cout, you have no variable named '?', which is where the argument / string is supposed to be, and that's what the compiler points to when it prints the errors you receive.
I'd recommend printing 'std::endl' or '\n' in the end of your printed string so the cin would be in a different line.
This is what is it should look like
#include <iostream>
int main() {
int passes; //The number of passed classes
int fails; // The number of failed classes
double grade; //The current grade to be analyzed
//Initialize number of passes and fails
passes = 0;
fails = 0;
//Prompt for first grade
std::cout << " Please enter a numeric grade(> 0)" << std::endl;
std::cin >> grade;
std::cout << "Received grade is " << grade << std::endl;
return 0;
}

What's causing this "invalid type argument of unary '*'"?

Ok, so I have researched as much as my tiny brain can take in. I have yet to find an answer that helps my problem. Trying to write a calculator that raises the base to a number no higher than 214783647. And as of now I'm jut trying to get the program to function without set values. But this is what the debugger says:
main.cpp: In function 'int main()':
main.cpp:25:11: error: invalid type argument of unary '*' (have 'int')
result = *x;
Here is the code.
#include <iostream>
using namespace std;
int solve(int, int, char);
int main()
{
int x = 0;
int y = 0;
int result = 1;
cout << "Enter your base:";
cin >> x;
cout << "Enter the number to raise base by:";
cin >> y;
for (x = 0; result <= y; result++)
{
result = *x;
}
cout << result;
return 0;
}
I am at the very beginning stages of C++, but I can take all constructive criticism.
FIXED!!
I'm not sure if this allowed, but I finally have the program fully functioning thanks to y'all!
The problem here is that your are trying to derefernece a variable that is not a pointer. Simply remove the * from result = *x; to assign the value of x to result.
However I don't believe you will get the desired effect. Because you are using x inside your loop and initializing it back to 0, you are clobbering whatever value your user has input.
I believe you are trying to do the following
int x = 1;
int y = 1;
std::cout << "Enter your base:";
std::cin >> x;
std::cout << "Enter the number to raise base by:";
std::cin >> y;
int result = x;
for(int i = 1; i < y; i++ ) { //loop y times
result = result * x; //exponents just times itself y times
}
std::cout << result << endl;
It's also worth mentioning that when using something from the standard library using the std:: namespace is good form, even if your compiler doesn't require it. As well as finishing any output with an endline endl, otherwise your terminal prompt will start right after the output. Hope that helps.

Including multiple files with C++

This week my class took a spin and is teaching material not found in the book. I'm using Visual Studio 2010, the project is to take 5 numbers from the keyboard and get the average, but I have to use functions with a .h header file and corresponding .cpp file to receive credit. This is what I have so far
Main.cpp
#include <iostream>
#include "average.h"
using namespace std;
const int numbersinput=5;
int main ()
{
int numbers,sum,avg;
cout << "Hello, please enter 5 numbers you would like to see the average for." << endl;
for (int i = 0; i != numbersinput; ++i)
{
cin >> numbers;
sum += numbers;
}
int average(int sum);
cout << avg;
system ("PAUSE");
return 0;
}
The .h headerfile named average.h
#include <iostream>
using namespace std;
int average(int);
and the other .cpp file named average.cpp
#include <iostream>
#include "average.h"
using namespace std;
const int numbersinput=5;
int avg;
int average(int sum)
{
avg = sum /numbersinput;
return avg;
}
I can get a successful build, but I get this error after I enter the first number and press enter.
Run-Time Check Failure #3 - The variable 'sum' is being used without
being initialized.
What am I not getting here?
You might want to initialize sum to 0 before you start adding to it with +=:
So instead of int numbers,sum,avg;
You will have int sum = 0; etc.
Change this line:
int numbers,sum,avg;
To:
int numbers=0;
int sum=0;
int avg=0;
This gives the variables values- before they are initialized (given a value) they are undefined, which means that they could equal any value. By initializing them, you are giving them a number to add to when you make the sum.
Edit these lines:
int average(int sum);
cout << avg;
To:
cout << average(sum);
The function declaration for int average(int sum) is not called in the same way as it is declared. The ints are unnecessary. In my edited code, you can see that the returned value (average)is printed out, instead of being left without being used.
Also, as a general tip, try not to give variables the same name. Try to make the function variable sum be called sumToAverage or instead make the sum in main be called total. It is a good idea to pick variable names that are different, so you won't get confused.
You're saying :
sum += numbers
But you haven't initialized sum, so it will have some random value that's on the stack. Change your declaration of sum to:
int sum = 0;
Also, you're using global variables to pass information to functions, which isn't a good idea. Get rid of the avg variable and change average to:
int average(int sum, int numberofvalues)
{
int avg = sum / numberofvalues;
return avg;
}
You're also re-declared average in the body of main, which you don't need to do as it's in the header. Then, you can get the average in main by saying:
int avg = average(sum, numbersinput);
Now, main will look like this:
int main ()
{
int sum=0;
cout << "Hello, please enter 5 numbers you would like to see the average for." << endl;
for (int i = 0; i != numbersinput; ++i)
{
int number;
cin >> number;
sum += number;
}
int avg = average(sum, numbersinput);
cout << avg;
system ("PAUSE");
return 0;
}
Oh, and don't put using namespace std in header files!

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