Simple exercise, lots of errors?

Pages: 12
Hello guys. I'm doing this exercise in C++ Primer Plus 5th edition. Bought it like $3 from eBay. Anyway this is the exercise "4. Write a program that has main() call a user-defined function that takes a Celsius temperature
value as an argument and then returns the equivalent Fahrenheit value. The program
should request the Celsius value as input from the user and display the result, as
shown in the following code:
Please enter a Celsius value: 20
20 degrees Celsius is 68 degrees Fahrenheit.
For reference, here is the formula for making the conversion:
Fahrenheit = 1.8 × degrees Celsius + 32.0"

And my source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

void result(); // create a function that does the conversion
int main(void);
{
    cout << "Please input a celcius value: "; // Gets input
    double celcius; // Creates a variable celcius type double
    cin >> celcius; // assigns input to celcius
    cout << celcius << "celcius is equal to" << result() << " fahrenheit!"; // prints the function results
    system("PAUSE");
    return 0;
}

void result() // function
{
     using namespace std;
     result = 1.8 * celcius + 32; // formula but I get an error here also.
}


I am soo not good with functions.. I read lots but don't quite get it..
consider what you're doing when you execute this line
 
cout << celcius << "celcius is equal to" << result() << " fahrenheit!"; // prints the function results 

you are trying to output the vaue returned by result()
Have a look at what that function returns exactly.

EDIT - Also, inside of the function 'result()'

 
result = 1.8 * celcius + 32;

what do you expect 'result' to be at this point? It is not a local variable and it is not a function as it is not followed by brackets '()' so what do you expect it to represent?
Last edited on
Also, Line 17 should not exist.
Omg seriousy I don't know!! this is so confusing >_< All im trying to do is
Ask for input
Get Input
Place input number in a variable
Call A function
that "function" does the calculation
Prints results to user

I've asked for input - cout << "Please input a celcius value: "; // Gets input
I've gotten the input -
I've placed the input in a variable cin >> celcius;
I've called the function - result()
The function does the calculations - void result() // function
{
using namespace std;
result = 1.8 * celcius + 32; // formula but I get an error here also.
}
And it prints results - cout << celcius << "celcius is equal to" << result() << " fahrenheit!"; // prints the function result

I will never learn something I don't understand without someone doing my work.
> I am soo not good with functions.. I read lots but don't quite get it..

That is what you need to get first. See if this helps; it may be a different way of looking at functions from what you have read so far.


A function is conceptually a set of pairs - the first component of each pair is an input value and the second component is the associated output value. Note: In mathemaics, what we call functions in C++ are called relations; an input is related to its associated output.

For example, the following set of pairs is conceptually defines a function:
F = { (1,2), (3,4), (5,6), (7,8) }.

The domain of the function is the set of all possible input values; in the example above the domain is:
{ 1, 3, 5, 7 }
.
The range of a function is the set of all possible output values; in the example above the range is:
{ 2, 4, 6, 8 }
.
We could write the above function as y = F(x) where x is an input value in the domain and y is the associated output or result value (which is in the range)

Or equivalently, F(x) = x+1 for x in { 1, 3, 5, 7 }.

In this example, the domain is a set of four integers, and so is the range. In C++, we would write the above function as: int F( int x ) ; It takes an integer as input and returns the associated integer as output.

So we could now write:
1
2
int input = 5 ;
int output = F(input) ;

When we call the function, we need to pass the input value and the result of the call is the associated output value. In the above example, the input value is the integer 5 and the corresponding output value is 6. The caller of the function supplies the input to the function when it is called, and the function returns the output associated with the input that was passed to it.

int F( int x ) ; only declares the function. To use it we must also define it.

1
2
3
4
5
6
int F( int x )
{
    int y ; // output or result ;
    // map the input x to the associated output and place it in y
    return y ; // return the output/result to the caller
} 


In this case, mapping input to output is easy:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int F( int x )
{
    int y ;
    if( x == 1 ) y = 2 ;
    else if( x == 3 ) y = 4 ;
    else if( x == 5 ) y = 6 ;
    else if( x == 7 ) y = 8 ;
    else 
    { 
       // there is an error made by the caller of the function 
       // input is not in the domain of the function
    }
    return y ; // return the result to the caller
} 


Alternatively,
1
2
3
4
5
6
7
8
9
10
11
int F( int x )
{
    int y ;
    if( x==1 || x==3 || x==5 || x==7 ) y = x+1 ;
    else 
    { 
       // there is an error made by the caller of the function 
       // input is not in the domain of the function
    }
    return y ; // return the result to the caller
} 


If we write
1
2
3
4
5
int F2( int x )
{
    int y = x+1 ;
    return y ; 
} 


The domain and the range of the function F2 is the set of all possible values that an int can hold; it still maps an input to an output.

For the function bool is_odd( int x ) { return x%2 == 1 ; }
the domain is the the set of all possible values that an int can hold; the range is { true, false } (the values that a bool can hold). The caller of the function must pass an integer as the input eg. is_odd(23) and we return the output as the result.

What you need to do for this exercise is

Write a function where
a. the input is a double value, say x - a temperature in Celsius
b. the output is also double value, say y - the associated temperature in Fahrenheit
c. the two are related by y = 1.8 * x + 32.0

for example, double to_fahrenheit( double x ) ;

Then write main which will accept the input value from the user, call the function passing the input value to it, and then print out the result which it returns.

Note: In the simple examples above, the input is a single value. It is also possible to write functions where the input itself is a set of values. For example, in
double function( int a, int b, int c ) ; the input is a set of three integers.
We'll cross that bridge when we come to it.
Last edited on
@Above post, I still cannot comprehend what your saying. I only just turned 14 btw and its confusing.. If anyone could do my exercise it would mean alot to me.
Here is a similar program:

4a. Write a program that has main() call a user-defined function that takes a 
kilometer distance value as the argument and then returns the equivalent 
miles distance value. The program should request the kilometer distance value as 
input from the user and display the result, as shown in the following code:

kilomers? 45.678
45.678 kilometers is 28.383 miles.

For reference, here is the formula for making the conversion:
distance in miles = 0.621371192 × kilometer distance


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

// function to convert a distance in kilometers to
// the equivalent distance in miles
double to_miles( double kms ) ; // declaration

int main()
{
    // accept distance in kilometers as input from the use
    std::cout << "kilomers? " ;
    double distance_in_kms ;
    std::cin >> distance_in_kms ;

    // use function to convert it to equivalent distance in miles
    // give it the  distance_in_kms as input
    // it returns the equivalent distance in miles
    double distance_in_miles = to_miles( distance_in_kms ) ;

    // print out the result
    std::cout << distance_in_kms << " kilometers is "
                   << distance_in_miles << " miles.\n" ;
}

double to_miles( double kms ) // definition
{
    double miles = kms * 0.621371192 ;
    return miles ;
}


Now try writing the Celsius to Fahrenheit program on your own.

Thank you JLBorges. I haven't started doing anything yet but I analyzed your code and I have a few questions?

1) At line 5 - "double to miles (double kms)" I understand that it creates a function named double to miles but what does the (double kms) do? Is it a variable used within the definition of the function?
2) At line 17 it creates a variable called distance in miles and assigns it the value of "to_miles" what is the purpose of "distance in kms" next to it?

At line 26 "double miles = kms * 0.621371192" what exactly is kms? is it pre-defined in C++? or is it a variable I don't get it? (I know kms is kilometres..)


closed account (zb0S216C)
By the looks of it, in result(), three things are wrong:

1) using namespace std shouldn't be there, as LB said
2) On line 18, you use result as a variable, but it's actually a function call that yields neither an R-Value or L-Value
3) On line 18, celcius isn't known to the compiler.

Wazzak
1) At line 5 - "double to miles (double kms)" I understand that it creates a function named double to miles but what does the (double kms) do? Is it a variable used within the definition of the function?
2) At line 17 it creates a variable called distance in miles and assigns it the value of "to_miles" what is the purpose of "distance in kms" next to it?
3) On line 18, celcius isn't known to the compiler.


You haven't made an attempt to read what had been posted earlier, have you?
Hey OP!
It doesn't matter what your age is.
Now as far as your question goes! You are having all sort of problems because you haven't studied enough! Before jumping into code, make sure you understand the syntaxes and logic behind the code you are trying to attempt! First, experiment with the codes that are already provided from books,manuals and web sites. Try to understand the code first then only proceed. Programming is not something that you can memorize. Its not like your regular subjects. Its a way of thinking!
So, just relax, take your time. Study more and more until you get the idea. Then jump into coding!
All the best!
I've actually read and studied alot for this. I've got 6 C++ books and I still don't get functions. I always seem to see different syntaxes of them.. I kind of understand how to define a function and tell it what to do but I'm not really knowledgable with the syntax of it. For example JLBorges "int F( int x ) ; only declares the function. To use it we must also define it." What purpose does int x serve? Is it the variable that will be assigned data once the function finishes? Also what is the difference between your function and this "void howthey();" . This function prints output.

Also I've made this simple program to try and test my knowledge of functions

The point is to create a function that doubles the number inputted by the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int GetCalc(int g);
int Number1;
int main()
{
    cout << "Enter a number to double" << endl;
    cin >> Number1;
    cout << Number1 << " doubled is " << int GetCalc(int g);
    system("PAUSE");
    return 0;
}

int GetCalc(int g);
{
    g = Number1 * 2;
    return g;
}

It seems right to me, but I get compiling erorrs bout 6! So I changed it abit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int GetCalc(int g);
int Number1;
int main(void);
{
    cout << "Enter a number to double" << endl;
    cin >> Number1;
    cout << Number1 << " doubled is " << int GetCalc(int g);
    system("PAUSE");
    return 0;
}

int GetCalc(int g);
{
    g = Number1 * 2;
    return g;
}
and I still get errors.

7 C:\Dev-Cpp\test134234.cpp expected unqualified-id before '{' token
7 C:\Dev-Cpp\test134234.cpp expected `,' or `;' before '{' token
16 C:\Dev-Cpp\test134234.cpp expected unqualified-id before '{' token
16 C:\Dev-Cpp\test134234.cpp expected `,' or `;' before '{' token

So I did this ..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int g;
int GetCalc(int g);
int Number1;
int main(){
    cout << "Enter a number to double" << endl;
    cin >> Number1;
    cout << Number1 << " doubled is " << int GetCalc(int g);
    system("PAUSE");
    return 0;

int GetCalc(int g);
    g = Number1 * 2;
    return g;
}


and got few errors
9 C:\Dev-Cpp\ok.cpp expected primary-expression before "int"
9 C:\Dev-Cpp\ok.cpp expected `;' before "int"
Any help?
Last edited on
Hello,

I'm new here and I'll try to help you.
First of all, you need to know something about functions.

Functions are "things that work for us". In the code below, the function increment(int n) receive a number, increment this number and return the result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;

int increment(int n);// This is the prototype

int main()             //Function main()
{
int number;          //Here we declare a variable to receive the number from the user
cout<<"Enter a number: ";
cin>>number;      //Here we put the number in the variable
cout<<"Incremented number is: "<<increment(number);  //Here we call the function and inform to the function that it must receive the value in the variable number to work. 
system("pause");
return 0;
}

int increment(int n)  //The value of the variable number is copied to the variable n.
{
n++;                     //The variable n is incremented
return n;               //The variable n, incremented, is returned to the main, in the line 11, where we
                          //called the function.
}



Your code working:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int GetCalc(int g); //It is the prototype. We need to use it because the function GetCalc(int g) is
                       //defined after the function main(). If you compile the program without it you will receive an error. Try it.
                       //Prototype is not necessary if you define the functions before the function main.
                       //but is better use prototype and define the function after the main


int main()//main() is a function. Did you know?
{
    int Number1;
    
    cout << "Enter a number to double" << endl;
    cin >> Number1;
    cout << Number1 << " doubled is " << GetCalc(Number1) << "\n\n";
    system("PAUSE");
    return 0;
}

int GetCalc(int g)      //Here is the function to double a value inputted by the user.
{                           //When we write "GetCalc(Number1)" in the main, tha value of the variable
                            //"Number1" is copied to the variable "g" of the function GetCalc
    g = g * 2;          //Here the value of the variable "g" is doubled
    return g;            //Here the value of g is returned to the line 16, where we call the function.
}


1- It's important to know that functions can have returns or not.

If you want a function that return something, you need:
int functionName(int n) or
float functionName(int n) or
double functionName(int n) or
char functionName(int n)

If you need a function without returns, you need:
void functionName(int n)


2- Functions can have parameters or not:
Functions with parameter: int functionName(int n)
Function without parameter: int functionName()
Can you see the difference?


There are several details. Ask me when you have doubts.

Good luck.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using namespace std;

// Declare the function. Include return type and type of values in parentheses
// so compiler knows what type to return and what type and how many values you
// may give the function
// Must declare (or define) function above code that uses the function (EDIT!)
int GetCalc(int g); 

int Number1;
int main(){
    cout << "Enter a number to double" << endl;
    cin >> Number1;
    // The function is called (used) in the next line
    // Do not include return type and argument type when a function is called
    // Number1 is the argument (variable in parentheses) passed to the function
    // In the function g will be given the same value as Number1. Think of g as a clone.
    // The function will not return g but an integer = g*2 and pass it to cout for display
    // Number1 is unchanged
    cout << Number1 << " doubled is " << GetCalc(Number1)<<endl;
    system("PAUSE");
    return 0;
}


// Define the function. Must include return type and parameter type as in declaration
// g inside the parentheses is known as parameter
// Must not define function inside another function
// You defined it inside main() in your code
int GetCalc(int g){ // g will be given the value of the variable you pass to the function
    return g*2; // Do to g what you want to do to the variable you pass to the function
// This function was declared to return an int so must return an int
// This function does not return g but an integer = g*2
}



Here is a beginner book to add to your collection that may help you understand functions.
http://greenteapress.com/thinkcpp/index.html (free ebook)

EDIT: oops too slow typing!
Last edited on
Thank you soooooo much @cassiospa and vin! your answers helped me alot! much more helpful than the books :)! However I have just one more question; double is supposed to be able to handle decimal numbers right? Mine isnt'? *The aim of the program is to convert light years into astornomical units*

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
double lightyears;
double astrounits(double z);
int main()
{
    cout << " Enter the number of light years: ";
    cin >> lightyears;
    cout << lightyears << " light years is equal to " << astrounits(lightyears) << " astronomical units! \n\n";
    system("PAUSE");
    return 0;
}

double astrounits(double z)
{
       z = lightyears * 63240;
       return z;
}


 Enter the number of light years: 3
3 light years is equal to 189720 astronomical units!


The answer is supposed to be 189 719.015 astronomical units

Any ideas?
Last edited on
> The answer is supposed to be 189 719.015 astronomical units

1
2
3
4
5
double astrounits(double z)
{
       z = lightyears * 63239.6717 ; // closer approximation than 63240  
       return z;
}


And then,
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    cout << " Enter the number of light years: ";
    cin >> lightyears;

    cout << fixed ; // **** print floating point values in fixed point notation
    // see: http://cplusplus.com/reference/iostream/manipulators/fixed/
    cout.precision(3) ; // **** with 3 digits after the decimal point
    // see: http://cplusplus.com/reference/iostream/ios_base/precision/

    cout << lightyears << " light years is equal to " << astrounits(lightyears) << " astronomical units! \n\n";
}


Last edited on
1
2
3
4
5
double astrounits(double z)
{
       z = z * 63240; // don't use lightyears in the function
       return z;
}



Well, 3*63240 is 189720.

Change the integer 63240 in astrounits to a number with a decimal (63239.6717?).

Last edited on
I'm just going to leave it at that I'm sure i'll figure it out eventually. Thanks JLBorges, vin, cassiospa, framework & quirkyusername :)
Well, before you leave it, check out this tiny program.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
    double a = 2 ;
    double b = 5.0 ;
    double c = 5.01 ;

    std::cout << a * b << '\n' ;

    std::cout << a * c << '\n' ;
}

Try using MinGW Developer Studio ? ... It's the best I have ever used...
Pages: 12