Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Write a function NumberOfPennies() that returns the total number of pennies given a number of dollars and (optionally) a number of pennies. Ex: 5 dollars and 6 pennies returns 506.
For the above question, here is the code below.
Getting an error: error: no matching function for call to 'NumberOfPennies(int)'
#include <iostream>
using namespace std;
int NumberOfPennies(int one,int two)
{
return (one*100+two);
}
int main() {
cout << NumberOfPennies(5, 6) << endl; // Should print 506
cout << NumberOfPennies(4) << endl; // Should print 400
return 0;
}
However, when I put int two=0 in the function NumberOfPennies it is working. Why is this so? Can anyone please explain this.
#include <iostream>
using namespace std;
int NumberOfPennies(int one,int two=0)
{
return (one*100+two);
}
int main() {
cout << NumberOfPennies(5, 6) << endl; // Should print 506
cout << NumberOfPennies(4) << endl; // Should print 400
return 0;
}
The fact that you have written int two = 0 in the second snippet is your supporting a default value of that parameter two of 0.
This means that it can be omitted at the calling site with the default value assumed if it is, so
cout << NumberOfPennies(4) << endl;
and
cout << NumberOfPennies(4, 0) << endl;
are equivalent. If you don't code your function to support a default value then you need to use two arguments to call NumberOfPennies.
(In order to improve readability consider renaming your parameters one and two to dollars and cents respectively).
There is a concept called default parameter in C++. Look up this link https://www.programiz.com/cpp-programming/default-argument.
In the first case, it is not able to resolve the function call to any existing function call taking just one integer parameter and fails.
int NumberOfPennies(int one,int two).
In the second case, int NumberOfPennies(int one,int two=0) as we have mentioned that if the second integer is not passed assume a default value of 0.During the first run compiler is not able to find a function that takes just one integer parameter. Next, it looks for possible cases where you have a function with 2 integer inputs with one of them having a default value. Your function matches this case and hence compilation is successful.
(Additional info: Its good to write function names and arguments that are intutive. Suggest you to rename arguments as int NumberOfPennies(int dollars,int cents))
"I ran the code below but it is not working"
is not a useful description of your problem.
Why is this so? Can anyone please explain this.
Your problem is clearly described in the compiler error report, which you should include in your post.
error: no matching function for call to ‘NumberOfPennies(int)’
std::cout << NumberOfPennies(4) << std::endl;
^
note: candidate: int NumberOfPennies(int, int)
int NumberOfPennies(int one, int two)
^~~~~~~~~~~~~~~
note: candidate expects 2 arguments, 1 provided
Thus, you tried to invoke the function with 1 argument, when your declaration requires 2.
By adding the default value for the second parameter,
int NumberOfPennies(int one,int two=0) ...
You have provided a value for the second parameter when not provided.
Review default function parameter.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have an array initialised like the following:
int example[5][5];
example[5][5] = 55;
And a function:
void example_function(auto inArray, int z){
cout << "example text = " << inArray[z][z] << endl;
}
And I am calling it into the function like this:
example_function(example, 5);
As you can see, I have the parameter for the function as auto when it is really using an integer array.
When I use typeid(table).name() to get the type of the array example, it outputs the type as A5_A5_i where the fives are from the initialisation (e.g. int example[3][4][5] would output A3_A4_A5_i)
When using typeid(table).name() on inArray after changing the type of the parameter from int to auto, I get the type name as PA5_i which is different to the one mentioned above.
How can I get a suitable type for a parameter in my function, and is there a better way to do this
If the array passed to the function is known beforehand, in this case as int example[5][5];, you can use the following,
void example_function(int (&inArray)[5][5], int z){
cout << "example text = " << inArray[z][z] << endl;
}
Here we take the array by reference to avoid array decay.
If the size might vary at runtime, use std::vector.
std::vector<std::vector<int>> example;
void example_function(std::vector<std::vector<int>> inArray, int z){
cout << "example text = " << inArray[z][z] << endl;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Hello I'm wondering how I can call functions within parameters in my class in main?
class processChoice {
public:
void processInput(string, int, string, int);
};
void processChoice::processInput(string processInput_UN,
int processInput_PC,
string initial_UN,
int initial_PC) {
for (; (processInput_UN != initial_UN) || (processInput_PC != initial_PC);
cout << endl) {
cout << "Enter your username: " << flush;
cin >> initial_UN;
cout << "Enter your 4 digit pincode: " << flush;
cin >> initial_PC;
cout << endl;
if ((processInput_UN == initial_UN) && (processInput_PC == initial_PC)) {
cout << "Access granted!" << endl;
} else {
cout << "Username and/or pincode doesn't match, try again..."
<< endl;
}
}
int main() {
userPinchoice Choice;
Choice.chooseUsername();
Choice.choosePincode();
cout << endl;
initial Values;
Values.initialUsername();
Values.initialPincode();
processChoice Input;
Input.processInput();
return 0;
What am I suppose to put in the round brackets at Input.processInput()?
I have been trying to get it to work but I just can't seem to access the function. I'm new to this so any help would be welcome.
Thanks in advance!
The bulk of your problem lies in the class processChoice. Here are some of such errors:
Firstly, the parameters specified in the function declaration in your class is faulty:
void processInput(string, int, string, int);
Here, you have only specified 4 data types, not variables. Kee in mind, these are variables that store the data that is passed from another function. In order to do this, you need to have these variables declared in the above line, variables with specific names that can be identified inside a function. You should have this line in your function declaration:
void processChoice::processInput(string processInput_UN, int processInput_PC, string initial_UN, int initial_PC)
This brings up another problem. Your function header is diffent upon declaration, and its header is different upon defining. The compiler sees it as 2 different functions. Therefore, you should keep your function headeer the same when declaring it and defining it.
Secondly, the for-loop inside your function has syntax errors:
for (; (processInput_UN != initial_UN) || (processInput_PC != initial_PC);
cout << endl) {
Firstly, judging from the syntax of the condition statement of the loop, it should be a do-while loop, not a for loop. Secondly, the cout << endl; should not be inside the condition statement of the for-loop; it should be implemented with the rest of the function. Thirdly, you do not put a semicolon at the end of your condition statement; it tells the compiler that this an empty loop without a body. Your loop should be something like:
do
{
cout << endl; // this is where you put the cout statement
// add rest of function code here
}
while ((processInput_UN != initial_UN) || (processInput_PC != initial_PC))
Another side note, why do you need 4 input parameters in your function? You take the pin number and username as input from the user, eliminating the need for 2 parameters. Something like:
string initial_UN;
int initial_PC;
If you declare this inside your function, just before the do-while loop I suggested above, then that eliminates these 2 variables from being parameters.
Now, to get to your question, if we have the following declaration:
Input.processInput();
Then we need to pass 4 parameters (2 if you follow my notes above) to it, and that is what the brackets next to the function name in this line of code a for. To pass a value to the function, simply, do the following (I'm only passing 2 parameters here, you can pass how many ever parameters you have defined in yout class only, not less or not more):
Input.processInput("Username", "password");
There are 2 input parameters that specify what the username and password should be. To differentiate the parameters being passed, syntax requires a comma to split them. You can also pass variables as arguments; however, make sure that you have initialized these variables.
This is a long post, so I may have made some errors I didn't notice. If there is any other mistake I noticed, then please inform me in the comments.
Good luck!
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 6 years ago.
Improve this question
int f_point(int kek,int *lol) {
*lol *= *lol;
return kek;
}
int main {
int x;
std::cin >> x;
int *adress_of_x = &x;
int a,b = f_point(x,&x); //how does it work?
std::cout << a << LINE_JUMP;
std::cout << b << LINE_JUMP;
}
For example, if I give 2 to program then I will get 0 and 2. Why?
b = f_point(x,&x) in this statement value of first parameter is 2.
Your function is not changing the value of first parameter and returns the same value.
Your are passing first parameter by value so it has no relation with the updated value of x. Variable a is uninitialized, so it is taking a garbage value.
int a,b = f_point(x,&x); //how does it work?
The variable declaration leaves a uninitialized and initializes b from the result of f_point(x,&x);.
Since it's an uninitialized variable, accessing the value of a in the
std::cout << a << LINE_JUMP;
statement leads to undefined behavior of your program. Having an output of 0 is just one of any possibilities (including your fridge explodes unexpectedly or little demons flying out of your nostrils).
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 6 years ago.
Improve this question
I have an assignment for school:
i. Create a classical Guitar object with price $150 and type = “classical”. Set the new price to $100 and display all the information about the Guitar object.
ii. Create an electric Guitar object with price $135 and type = “electric”. Change the price as there is a promotion and display all the information about the Guitar object.
I am trying to solve it on my own, but I am new in C++ and I'm stuck with compiler errors that I can't understand.
Here the class that I have created in my Guitar.h file.
#pragma once
#include<iostream>
#include <string>
#include<sstream>
using namespace std;
class Guitar
{
private:
string type;
double price;
public:
Guitar(string type, double price);
string getType();
double getPrice();
void setPrice(double newPrice);
void setPrice(bool promotion);
string toString();
};
This is the class implementation in my Guitar.cpp file
#include "Guitar.h"
Guitar::Guitar(string typeclass, double priceclass)
{
type = typeclass;
price = priceclass;
}
string Guitar::getType()
{
return type;
}
double Guitar::getPrice()
{
return price;
}
void Guitar::setPrice(double newPriceclass)
{
price = newPriceclass;
}
void Guitar::setPrice(bool promotion)
{
if (promotion == true)
price *= 0.9;
}
string Guitar::toString()
{
stringstream info;
info << "Guitar Type: " << type << endl
<< "Price: " << price << endl;
return info.str();
}
Finally I have my main file GuitarApp.cpp
#include"Guitar.h"
int main()
{
Guitar guitar1("Classical", 150.0);
guitar1.setPrice(100) << endl;
cout << guitar1.toString() << endl;
Guitar guitar2("Electrical", 135.0);
guitar2.setPrice(true);
cout << guitar2.toString() << endl;
}
I have 2 errors:
more than one instance of overloaded function Guitar::setPrice matches the argument list
Guitar::setPrice ambiguous call to overloaded function.
Can someone explain to me the errors and what I should do to get the code compiled?
Edit: After having changed 100 to 100.0, I got 4 more errors:
mismatch in formal parameter list
expression must have integral or unscoped enum type
cannot determine which instance of function template std::endl; is intended
'<<': unable to resolve function overload
All errors are on line 7 of my GuitarApp.cpp which is
guitar1.setprice(100.0)<<endl;
If i were to edit the price of the guitar from 100.0 back to 100, I would get the two error that I initially had.
The type of the literal 100 is int. Since int is just as easily convertible to bool as it is to double, it's ambiguous which of those functions should be called.
Changing 100 to 100.0 (a double literal) should fix this.
Normally we did not fix home works here. It is better to ask "Why this line of code did not work" instead of throwing a bunch of homeworks here in the hope to get it made ready from others...
Please also get in mind that your question is "Off topic" because:
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers.
OK, your code have following syntax bugs:
guitar1.setPrice(100.) ; // see the "." behind the number!
You have to methods:
void setPrice(double newPrice);
void setPrice(bool promotion);
And you wrote:
guitar1.setPrice(100)
100 is an int and not a double and not a bool. So the compiler can not decide to make from your 100 a bool which has value true or make it a double with value 100.. So simply add a dot to make your value a floating point one which your compiler takes as double.
Next bug:
cout << guitar2.toString() << endl; // see the "2" behind guitar !
Only a typo...
Some remarks:
Splitting such a class in a header and a source file is bad! The optimizer has no chance to inline the functions.
Using using namespace std; can be bad! It is much better to write std::string and all you need to see from which namespace your definition comes. That makes a bit more work but is much better to read later, especially if you use multiple namespaces from multiple libraries.
Explanation:
It is easy to save typing some characters at a first view. But if you later (re-)use your code in an bigger application where you have to deal with a lot of libraries which may define functions/classes/what ever with the same name as one of the other library do, you start changing your code.
A simple example is to have posix read and istream read in place. Here it is also a good idea to give a '::read' to select the posix one which is not bound to a namespace.
Is it dogmatic to give the hint to not use using namespace? My personal experience is simply that if you use it, you may run into problems if your code is (re-)used later in bigger applications. And for me it is mandatory to write my code as such, which can be (re-)used without problems and or a lot of adoptions/corrections in future.
You have to decide: Save some characters to type today and may run into trouble later or do the job right now.
Maybe for the homeworks code is ok to do so. But I believe it is a good point to talk about the problems which may arise on that kind of code writing.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have wondered about template optimizing. Look at the sample code:
....
template <class T>
T AReallyBigFunction(T); //size = a (MB)
....
int main(){
....
short number1;
int number2;
long number3;
cout << AReallyBigFunction(number1) << endl;
cout << AReallyBigFunction(number2) << endl;
cout << AReallyBigFunction(number3) << endl;
....
}
The question is: All three of number1, number2 and number3 always give the correct result with AReallyBigFunction<long>, but I don't want to notice to template parameter long and I don't want to multiply unneccessary program size, Does gcc/g++ can do it?
EDIT
size of AReallyBigFunction<T> equal to a MB for each class T. So, If call AReallyBigFunction with three various integer type, total size is 3*a MB. If I always call AReallyBigFunction<long> (with template parameter class T has been specified to long), the size is a MB. I want the compiler always calls AReallyBigFunction<long> although I just write AReallyBigFunction (without specifying class T, with any integer value (short, int or long)). My question is: does gcc/g++ has any solution (compiling mode) to respond me?
If the comment by #DrewDormann is correct interpretation of the question, then you can use the following trick to reduce code size.
Define function overloads that take an int and short and call the function template using long.
int AReallyBigFunction(int in)
{
long res = AReallyBigFunction<long>(in);
return static_cast<int>(res);
}
short AReallyBigFunction(short in)
{
long res = AReallyBigFunction<long>(in);
return static_cast<short>(res);
}