cannot convert 'double(_cdecl*)()' to 'double' - c++

As an assignment I have to write a code that takes user inputs, performs an operation with them, then prints them to the screen. However, I keep getting an error on line 18 where I call FunctionMultiply saying that the function cannot convert 'double(_cdecl*)()' to 'double'. I searched for this type of problem but it seems like all of them have to do with arrays which aren't in my code. How can I fix this?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
int GetInt(void);
double GetDouble();
char GetLetter(void);
double FunctionMultiply(int, double);
int FunctionCharacter(char);
int main()
{
GetInt();
GetDouble();
GetLetter();
FunctionMultiply(GetInt, GetDouble);
FunctionCharacter(GetLetter);
printf("%f", FunctionMultiply);
printf("%c", FunctionCharacter);
return 0;
}
int GetInt(void)
{
int integer;
printf("Enter an integer\n");
scanf("%i", &integer);
return integer;
}
double GetDouble()
{
double dub;
printf("Enter a floating point number\n");
scanf(" %lf", &dub);
return dub;
}
char GetLetter(void)
{
char letter;
printf("Enter a letter\n");
scanf(" %c", &letter);
return letter;
}
double FunctionMultiply(int arg1, double arg2)
{
double product = arg1 * arg2;
return product;
}
int FunctionCharacter(char letter)
{
if (toupper(letter) <= 'M')
{
return 0;
}
else
{
return 1;
}
}

I think you are confusing function identifiers with storage. You have just called a bunch of functions at the beginning and not stored their results in anything.
It appears that you expect using the function identifier on its own will give you the result of the last call to that function. But it does not.
Here is how you would store the return values and use them later:
int my_int = GetInt();
double my_double = GetDouble();
char my_char = GetLetter();
double multiply_result = FunctionMultiply( my_int, my_double );
char char_result = FunctionCharacter( my_char );
printf( "%f", multiply_result );
printf( "%c", char_result );

Modify your main() like this:
int main()
{
int i = GetInt();
double d = GetDouble();
char c = GetLetter();
double a = FunctionMultiply(i, d);
char c = FunctionCharacter(c);
printf("%f", a);
printf("%c", c);
return 0;
}
Your problem is that you are passing function names rather than calling them. i.e. GetInt instead of GetInt().

It looks like you weren't paying attention to the lessons or examples showing how to use functions.
GetInt();
This calls the GetInt function, and ignores its return value.
GetDouble();
This calls the GetDouble function, and ignores its return value.
GetLetter();
This calls the GetLetter function, and ... you know the score by now.
FunctionMultiply(GetInt, GetDouble);
This is just nonsense. You're trying to call the FunctionMultiply function, passing the functions GetInt and GetDouble as arguments. You need to pass it an int and double, but you don't have an int and a double because you didn't store the results of GetInt and GetDouble anywhere.
You should have done this:
int i = GetInt();
double d = GetDouble();
char l = GetLetter();
Now you have variables i, d and l that hold the results of those function calls, so you can pass them in to other functions:
FunctionCharacter(i, d);

You seem to be under the impression that the name of a function magically changes to the result of the call, after you've called the function once.
It doesn't. The function call expression itself is the result of the call.
Instead of
ReturnADouble();
// call ^ and value v somehow separated? Why did you ever think that?
double result = ReturnADouble;
But according to the language rules, ReturnADouble is still the name of a function, and the compiler righteously complains when you give the name of a function when you should be giving a numeric value.
Your code should read more like
double result = ReturnADouble();
// ^ this call results in a value

Related

Why do I get the "identifier "a" is undefined" in a function where I have a as a parameter?

In the following code:
void benchmark(string desc, int(*pf)(int a[50])) {
printf("\n Benchmark for %s", desc.c_str());
double tStart = omp_get_wtime();
int result = pf(a[50]);
double tFinal = omp_get_wtime();
printf("\n\t Final result: %d", result);
printf("\n\t Duration: %f (s)", tFinal - tStart);
int main() {
int i, b;
int a[50];
for (i = 0; i < 50; i++)
{
b = rand() % 10000 + 1;
a[i] = b;
}
benchmark("Parallel solution without mutex for counting primes", Squential);
benchmark("Parallel solution with load balancing", Parallel1);
benchmark("Parallel solution with load balancing", Parallel2);
}
On line "int result = pf(a[50]);" the compiler says "identifier "a" is undefined" although I listed it in the parameters list. It may have something to do with the pointer, I'm not used to working with pointers.
This does not have a parameter a
void benchmark(string desc, int(*pf)(int a[50])) {
This has the parameters:
* desc: Type -> string
* pf: Type -> A function (pointer) that returns int and takes an array of int
This is a function pointer type:
int (*pf)(int a[50])
^^ This is the name of the paramter.
// This is the type
int (*)(int[50])
// This is a pointer to a function that returns an `int`
// and takes `int[50]` as a parameter.
Just to get this copiling do this:
int result = pf(a[50]);
// change into this:
int data[50]; // or get this from somewhere else.
int result = pf(data);

using the return value of one function as an argument in another function in c++

I found some related answers but couldn't understand it clearly because the codes were complicated for me.
In this program I used the dif () to find the difference in price then stored the return value total in variable difrnc. Then I used the difrnc variable as an argument for the function call
inflation=inflan(difrnc,lyp) //(calculates the inflation)
Instead of storing the total in variable difrnc can I directly use the answer from the function dif() as an argument for the function inflan() in its definition and how?
Sorry if it is a repeated question it would be great if someone could explain it using this program.
#include<iostream>
using namespace std;
double dif(double lp,double cp);//cp= current price,lp= last price, current
double inflan(double difference,double lastyp);
double cost(double cp,double inrate);
int main()
{
double lyp,cyp,difrnc,inflation,one_year_cost; // lyp = last year price,cyp=current year price,
for(int i=0;i>=0;i++)
{
cout<<"Enter current years price :";
cin>>cyp;
cout<<"Enter last Years price: ";
cin>>lyp;
difrnc=dif(lyp,cyp);
if(difrnc<0)
{
cout<<"price decreased by "<<difrnc<<endl;
}
else
{
cout<<"price increased by "<<difrnc<<endl;
}
inflation=inflan(difrnc,lyp);
one_year_cost=cost(cyp,inflation);
cout<<one_year_cost<<endl;
}
}
// to find the difference in price
double dif(double lp,double cp)
{
double total;
total=cp-lp;
return(total);
}
// to find the inflation
double inflan(double difference,double lastyp)
{
double inrate;
inrate=difference/lastyp;
return(inrate);
}
// to find estimated cost in one year
double cost(double cp,double inrate)
{
double
totalc=cp+inrate;
return(totalc);
}
Yes you can like this inflatio n = inflan(dif(lyp,cyp),lyp);
However, since you use the function returned value more than once, it make more sense to keep it as it is.
Aside from your current issue in your functions you can simplify them by removing their local variables and just simply return the evaluated expression.
For Example: You have this ->
double cost( double cp, double inrate ) {
double totalc = cp + inrate;
return totalc;
}
It is safe and efficient to do this instead:
double cost( double cp, double inrate ) {
return cp + inrate;
}
You can do that for any simple function that doesn't go through any loops.
As for your actual issue check out this quick program;
Sample.cpp
#include <iostream>
int five() {
return 5;
}
int ten() {
return 10;
}
int add( int a, int b ) {
return a + b;
}
int main() {
std::cout << add( five(), ten() ) << std::endl;
return 0;
}
Set a break point within the first line of your main function and step through the code line by line while examining your stack calls as well as your local and auto variables to see what is happening on each line of your functions to see the values that are being assigned to each variable.

How do I return value to main function without directly calling the function

I have multiple functions in my program. Each function has some conditions. If conditions are met, then it passes on the value to another function which again checks the value with some conditions, modifies it.
The first function [named 'squarefree()'] is called from main [obviously] and it further goes on to call another function which in course calls another function untill the process stops at last function named 'end()'. Like this:
#include <iostream>
using namespace std;
int squarefree(int n);
int goodnumber(int sf);
int end(int gn);
int main() {
// your code goes here
int l,r;
cin>>l;
cin>>r;
for(int p=l;p<=r;p++)
{squarefree(p);}
/*int ret=end(int gn); PROBLEM LIES HERE
cout<<ret; */
return 0;
}
int squarefree(int n){
int i;
for(int i=2;i<n;i++)
{
if((n%(i*i))==0)
{
cout<<"number not square free"<<endl;
break;
}
else{
cout<<"number square free"<<endl;
goodnumber(n);
break;
}
}
return 0;
}
int goodnumber(int sf){
cout<<"Sf is:"<<sf<<endl;
int s=0,c=0,flag=0;
for(int j=1;j<=sf;j++)
{
if(sf%j==0)
{
s+=j;
for(int k=2;k<=j/2;++k)
{
if(j%k==0)
{
c++;
}
}
}
}
cout<<"s is:"<<s<<endl;
cout<<"no.of prime numbers dividin s are:"<<c<<endl;
for(int l=2;l<=c/2;++l)
{
if(c%l==0)
{
flag=1;
break;
}
}
if (flag==0)
{cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
end(s);
}
else
{cout << "C is not a prime number"<<endl;
}
return 0;
}
int end(int gn)
{
int sum=0;
sum+=gn;
cout<<"SUm of factors of the good number is:"<<sum<<endl;
return sum;
}
The 'end()' function returns a value sum. Now I want this value sum to be updated everytime the for loop in main() function runs. For example: Sum in first iterations is 5, sum is 2nd iteration is 10, so total sum gets 15 and so on.
If somehow, the value returned by end function can be fetched into main function, that would be great.
Look at all those int-returning functions that are always returning 0. You might be able to take advantage of that.
A trivial example:
#include <iostream>
int step3(int val)
{
return val * val;
}
int step2(int val)
{
return step3(val + 1);
}
int step1(int val)
{
return step2(val * 2);
}
int main()
{
std::cout << step1(1);
}
But take care. You might find a case where you don't get any valid results and need to inform the caller that no result was found.
In addition to the idea of having the functions return the result of the next stage in the pipeline, which is an excellent idea, you can pass the address of the variable in which to store the result (allowing you to return more than one result, or an error code), or store the result of each stage in a temporary variable and return that (allowing you to use a result in more than one computation). I would advise against using a global variable to bypass the stack; it’s considered poor practice.
Some Examples:
// Returning the result of the next stage in the pipeline:
int g(int);
int f(int x)
{
return g(x);
}
// Passing a variable by reference:
enum errcode { success, failure };
errcode sqr( int input, int& output )
{
output = input * input; // This modifies the second variable the caller gave.
return success;
}
// Storing in a temporary variable:
int stage2(int);
int stage1(int x)
{
const int y = stage2(x); // Store the result in a temporary.
const int z = sqr(y);
return z;
}
// Passing results through a global variable is a bad idea:
int necessary_evil = 0; // Declared in global scope; should at least be
// declared static if possible to make it visible only in this source file.
// Namespaces are a fancier way to do something similar.
void kludge(int x)
{
necessary_evil = x * x; // The caller will check the global.
return;
}
There are examples of all of these in the standard library: printf() is essentially a wrapper for vfprintf(), strtol() takes a parameter by reference that the function sets to a pointer to the remainder of the string, and errno is a global variable.

C++ Boolean statement errors (I think)

This program is supposed to ask for an integer, if you want to add or subtract, then another integer, then do the math, but it declares both subtraction and addition as false inputs and i think there are errors in my boolean. Any help is appreciated.
/***********************************************************
Program Name: Simple Math Calculator
Program Author: Kyle NoCompile
Date Created: 9/12/16
Program Description:
This program performs simple arithmetic calculations.
The user enters numbers and the math operation to
perform on those numbers. The program will then display
the result of the operation.
Modified Date:
Modified Description:
***********************************************************/
#include <iostream>
using namespace std;
// Function prototypes:
void showWelcome();
int getUserIntegerInput();
char getMathChoice();
int getInteger(bool);
bool validateMathChoice(char choice);
int doAddition(int int1, int int2);
int doSubtraction(int int1, int int2);
int doMath(int firstInt, int secondInt, char mathFunc);
int showResult();
// This is the main function (where the program begins)
int main()
{
// Variables to hold local data
int firstNum;
int secondNum;
int mathChoice;
int result;
// Call the showWelcome() function
void showWelcome();
// Call the getInteger() function (for the first integer)
// and store the result in the "firstNum" variable
firstNum = getInteger(true);
// Call the getMathChoice() function and store result in "mathChoice" variable
mathChoice = getMathChoice();
// Call validateMathChoice() function, passing it the user's math choice
// and using the return value to decide what to do next
if (validateMathChoice() = true)
{
// Call the getInteger() function (for the second and subsequent integers)
// and store the result in the "secondNum" variable
secondNum = getInteger(false);
// Call the doMath() function and pass it all of the user input
// and store the return value in the "result" variable.
int result = doMath(firstNum,secondNum,mathChoice);
// Call the showResult() function to show the result
int showResult(int result);
}
else
{
// If the user chose an invalid math function...
cout<<"Not a valid math choice"<<endl;
}
return 0;
}
// This function shows a nice welcome message
void showWelcome()
{
cout<<"******************************************"<<endl;
cout<<"Welcome to the simple calculator program!"<<endl;
cout<<"This program will do simple addition and"<<endl;
cout<<"subtraction. Math is fun, so enjoy!"<<endl;
cout<<"******************************************"<<endl;
}
// This function gets integer input from the user
int getUserIntegerInput()
{
int input;
cin>>input;
return input;
}
// This function asks the user for a math function
// and returns the user's input
char getMathChoice()
{
char choice;
cout<<endl<<"Please select a math function to perform (\"+\" = Addition, \"-\" = Subtraction): ";
cin>>choice;
return choice;
}
// this function asks the user for either the first integer
// or the second and returns the user's input
int getInteger(bool firstNum)
{
cout<<endl<<"Please enter the ";
// if the "firstNumber" variable is true, then this
// is the first number being collected
if (firstNum)
{
cout<<"first ";
}
// Otherwise, it's the second number being collected
else
{
cout<<"second ";
}
cout<<"integer: ";
// Call the getUserIntegerInput() function and return the return value from it
return getUserIntegerInput();
}
// This function validates the user's match function choice
// by returning a true for valid, and a false for invalid
bool validateMathChoice(char choice)
{
if (choice == '+' || choice == '-')
{
return true;
}
else
{
return false;
}
}
// This function adds two integers
int doAddition(int firstInt,int secondInt)
{
return firstInt + secondInt;
};
// This function subtracts the second integer
// parameter from the first integer parameter
int doSubtraction(int firstInt, int secondInt)
{
return firstInt - secondInt;
};
// This function determines the result of the math
// operation requested by the user
int doMath(int firstInt, int secondInt, char mathFunc)
{
// Initialize result to zero (0)
int result = 0;
// If the math function is a "+", then call the
// doAddition() function and store the return
// value in the "result" variable
if (mathFunc = '+')
{
result = doAddition(firstInt, secondInt);
return result;
}
// If the math function is a "-", then call the
// doSubtraction() function and store the return
// value in the "result" variable
else (mathFunc = '-');
{
result = doSubtraction(firstInt, secondInt);
return result;
}
return result;
}
// This function displays the result of a math operation
int showResult(int result)
{
cout<<endl<<"The result is "<<result<<endl;
}

invalid conversion from 'int' to 'QString*'

Basically im returning trying to return the integer counter to my main program however I get the error message of:
invalid conversion from 'int' to 'QString*' [-fpermissive]
return counter;
even though counter is an integer. This is probably a very simple fundamentals problem and I apologize for that but any input/explanations would be greatly appreciated.
function:
QString* MainWindow::sort(QString* a, int n, QString na)
{
int yes = 1, i;
int counter=0;
int j=0;
for (i = 0; i < n; ++i)
{
if (a[i] == na)
{
counter++;
qDebug() << "Found a duplicate of " << a[i];
yes = 0;
}
}
if (yes)
{
qDebug() << "No duplicates";
}
qDebug() << counter;
return counter;
}
In order to return a pointer to QString you can create a QString on a free store using copy constructor which will take a QString created from your counter which is int:
QString* MainWindow::sort(QString* a, int n, QString na)
{
int yes = 1, i;
int counter=0;
//...
return new QString( QString::number( counter));
}
Your code couldn't compile because of lack of possibility to implicitly convert int to QString. You shouldn't however pass pointers to QString, just return a QString.
QString MainWindow::sort(QString* a, int n, QString na)
{
int yes = 1, i;
int counter=0;
//...
return QString::number( counter);
}
The problem is simple; your function is supposed to return a QString * (according to QString* MainWindow::sort( ... )), but you're trying to return counter, which is an int (according to int counter = 0;).
C++ won't implicitly convert an int to a QString * - if that's really what you want to do (in this case, this isn't what you want to do), you'd need to cast it explicitly, with something like static_cast<QString *>(counter);.
However, in your case, you've just got a mismatch, and you should decide - do you want to return counter, or do you want to return the string? In the first case, you'd change your function declaration to int MainWindow::sort( ... ) (This is what you said you wanted to do in your OP.).
In the second case, instead of saying return counter;, you need to say return a; or similar. However, since the function is operating on the string in-place (i.e., not on a copy of it), this isn't really neccessary.
Your function is declared as returning QString* and you're returning an integer. This is a mismatch.
I think the real 'fix' is to correct the function prototype to return an integer int MainWindow::sort(QString* a, int n, QString na) or if this isn't under your control, then you're not implementing the function right.
An integer expression (except a constant integer expression with value 0) may not be implicitly converted to a pointer. And the error message says about this restriction.
Also it is totally unclear why you are goint to convert the counter to a QString pointer/