LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C++ Basic Function Help, PLS. (https://www.linuxquestions.org/questions/programming-9/c-basic-function-help-pls-345205/)

InvisibleSniper 07-20-2005 08:51 PM

C++ Basic Function Help, PLS.
 
Having trouble trying to utilise a function in my C++ program that I wrote. It prompts the user for a mesurement to be converted to centimetres.

Two things I would like to know about it is would this program work and how could I use the 'return' feature in this program?


Code:

#include<iostream>

using namespace std;

void MyFunction(float OneMile = 182880, float OneKiloMetre = 100000.00, float OneMetre = 100.00
float OneFoot = 12.48, float OneInch = 2.54);
int main()
{

cout<<"What would you like to convert to centermetres? "
int ToBeConverted = 0;

cout<<"1.)Inches"<<endl;

cout<<"2.)Feet"<<endl;

cout<<"3.)Metres"endl;

cout<<"4.)Miles"<<endl;

cout<<"5.)Kilometres"<<endl;

cin>>ToBeConverted;
/*Can I somehow put the functions in a switch and if the user chooses that option
the swith will 'return' the correct part of the function?*/
float InchesConversion = 0;
float FeetConversion =0;
float KiloMetreConversion = 0;
float MileConversion = 0;
float MetreConversion = 0;
switch(ToBeConverted)
{

case 1:

//e.g in this case is only an example of what I mean.
cout<<"Enter how many Inches you want converted to centimetres: "<<endl;
cin>>InchesConversion;
cout<<"The conversion of "<<InchesConversion<<" inches to centimetres is "<<OneInch * =InchesConversion;
break;


case 2:

case 3:

case 4:

case 5:
}


kite10linux 07-20-2005 09:04 PM

C program - very similar
 
#include <stdio.h>

float fnConvert(float inches);

void main(void)
{
float x1=0, x2=0;

printf("\nEnter number to convert to inches.");
scanf('%f", x1);

x2=fnConvert(x1);
printf("\n %f centimeters in inches = %f \n");

return;
}

float fnConvert(float temp)
{
return(temp/2.54);
}
/ * ******************************* to use the switch statement:

with input variable "x"

switch (x)
{
case 1: ...call function 1
break;
case 2: ... call function 2
break;
etc.
default: break;
}

******************************************************************************/

InvisibleSniper 07-20-2005 09:17 PM

Man, that is so confusing. I am use to cout<<"" but so many people use scanf and printf. I think it's also because I don't know how to return multiple values yet, does anyone know a good guide on it that is easy to read examples(with not too advanced code)? Little bit lost, sorry I still would like some furture help.

Thanks anyway.

P.S fastest reply I have come accross.

sind 07-20-2005 11:29 PM

Hmm, it might be easiest and more modular to create a number of functions, each with their own purpose. For example, this is how I would do a inches to centimetres function in C (it shouldn't be too different in C++ but I guess #define'd constants are frowned upon):

Code:

#define INCHES_FACTOR 2.54

int inches_to_cm(int inches)
{
    return (inches * INCHES_FACTOR);
}

Then you can call that function from your menu function or main() function:

Code:

int main()
{
    int conv = 0, value = 0, result = 0;

    ... code to ask user value and conversion, value stored in 'value', conversion stored in 'conv'  ...

    switch (conv)
    {
        case 1:
            result = inches_to_cm(value);
            break;

        ... more conversions ...
    }

    ... output ...
}

Another way you could do it would be to have one function that accepted an imperial value and a factor, like so:

Code:

#define INCHES_FACTOR 2.54
#define FOOT_FACTOR 30.48

int convert_imperial_to_cm(int value, int factor)
{
    return (value * factor);
}

int main()
{
    ... code as above main function ...
    ... switch statement used to store factor in 'factor', say FOOT_FACTOR ...

    result = convert_imperial_to_cm(value, factor);

    ... value converted from feet to centimetres and stored in result ...
}

The second method is perhaps more efficient as far as code size goes, but the first is probably more in the spirit of C++ as another class can call an inches_to_cm function without knowing the factor to use.

Hope that gives you some food for thought.

~sind

kite10linux 07-21-2005 01:09 AM

#include <iostream.h>

int main(void)
{
int iChoice;

cout << "Enter in Choice : " << endl;
cout << "Convert from inches to 1. feet, 2. centimeters" << endl;
cin >> iChoice;

cout << "You entered " << iChoice << endl;

if ((iChoice < 1) || (iChoice > 2))
{
cout << "error." << endl; return -1;
}

switch(iChoice)
{
case 1: cout << "Inches divided by 12 = feet" << endl;
break;
case 2: cout << "Inches times 2.54 = centimeters"<< endl;
break;
default: break;
}

cout << "Done." << endl;

return 0;
}

elyk1212 07-21-2005 01:15 AM

Hi, you need to get books on generic programming concepts. It is not so much C/C++ that you need to learn, but the good old heart of lambda calculus programing concepts. C++ examples will also help you learn, nothing better than seeing something that works and working from this. May I suggest "Practical C++" By O'Reilly. A great book for learning programming and even deeper C++ incite.
Anyhow, as you might already know, you cannot return multiple values. You *can* however pass references to variables with side-effects meaning this.

Code:

int some_function(int& integer, int& cool)
{
  integer = 7 + integer;

  // Another way to write this is
  // integer += 7;

  cool = 5;
}

Now if I were to call this function from main, like so
Code:

int main(void)
{
    int i = 1;
    int a = 1;
  some_function(i, a);

  /* Now here 'i' would equal 8
        and 'a' would equal 5, *sort of* returning 2 things, but NOT REALLY.
        The reference to these variables were passed to some_function and changed
        at that memory location */
}

See what I mean? Not really returning 2 things, a return statement only returns one
"Thing". But this could be a struct or Object (in C++) that contains many data.

lowpro2k3 07-21-2005 01:35 AM

Quote:

Originally posted by InvisibleSniper
Man, that is so confusing. I am use to cout<<"" but so many people use scanf and printf. I think it's also because I don't know how to return multiple values yet, does anyone know a good guide on it that is easy to read examples(with not too advanced code)? Little bit lost, sorry I still would like some furture help.

Thanks anyway.

P.S fastest reply I have come accross.

Don't worry, it takes a bit of time.

A few things I noticed from your reply:

Quote:

I am use to cout<<"" but so many people use scanf and printf
The printf(...) and scanf(...) set of functions originate from C. You're bound to cross that path eventually, so try to gradually read what each is doing and see if you can write your own versions. But remember you're focusing on C++ right now, they are different languages.

cout and its family are better for C++ programming for a variety of reasons I wont get into right now so stick with cin/cout, but maybe try and learn a bit about printf and scanf (hint: research "format strings").

Quote:

I think it's also because I don't know how to return multiple values yet
Since you're just starting out with functions, I imagine you haven't learned much yet about classes and objects, structures, or other user defined types (UDT's). So the basic answer for where you are is "you can't return multiple values". But I cringe when I say that because its oh so wrong, you're just not quite there yet. I'll try to guide you a little on the right path.

Heres a simple function that takes 2 integer values and returns the sum, along with a simple C++ program that uses the function.

Code:

#include <iostream>
using namespace std;

int calcSum(int first, int second)
{
    return (first + second);  // parenthesis probably not needed
}

int main()
{
    int v1, v2, sum;

    cout << "Enter value 1: ";
    cin  >> v1;

    cout << "Enter value 2: ";
    cin  >> v2;

    sum = calcSum(v1, v2);
    cout << "Sum of values is " << sum << endl;

    return 0;
}

Lets say you want to write a slightly more complex function. Lets write a function that recieves three integer values meant to represent coordinates in 3d space. We'll assume the function needs to do some processing on these coordinates, then somehow give the calculation results back to the caller. Well, in C++ there is no way to simply "return 3 integers". But remember, in C++ you can create your own types, so it would make sense to create our own "3dPoint" type. This new type will store 3 integers, its probably easier to see in code.

Note: I will use a C++ class to show you how to do this, simply out of my own preference. A C-style "struct" would also work well in this situation, but I'll try not to confuse you any more ;) One more thing, I dont want you to get confused on constructors yet, but I'm going to add a very simple constructor to the class. Every time an object gets created from this class, this "constructor" will get called ONCE and only once. It will set all values to 0, this is just good practice (initializing all your variables to appropriate values).

Code:

#include <iostream>
using namespace std;

class 3dPoint
{
public:
    int x, y, z;
    3dPoint() { x = y = z = 0; }
};

3dPoint calcPointValues(int x, int y, int z)
{
    3dPoint point;
    point.x = x + 5;
    point.y = y - 3;
    point.z = z + 18;

    return 3dPoint;
}

int main()
{
    3dPoint pt;
    pt = calcPointValues(15, 12, 10);

    cout << "Point values: x = " << pt.x << " y = " << pt.y << " z = " << pt.z << endl;
    return 0;
}

I dont like using the public qualifier in classes more than I need to, but in this case it saved me alot of explaining of certain concepts you dont need to know yet. But I hope this helped a bit. Remember you dont learn C++ over night, so just keep practicing, reading and writing code, and asking help of others when you dont understand things.

InvisibleSniper 07-21-2005 09:51 AM

Wow, that was totaly amazing. It was like the code turned into a 3D game and jumped out at me saying, "This is how I work". Damn, I'm actually starting to understand now, thanks for all of your help.

I'm going to get back to learning some more 00P language :).


Once again, thanks.:)

::EDIT::

I have attached my source code for the centimetre conversion program. I was hoping that someone could correct it, as it isn't working for some reason. But if they could also leave the structure as it is(like no, printfs or functions) because I want to see what I've done wrong. Just to correct the syntax or similar.

In advance thanks from noo:newbie: programmer.

P.S This is a great forum, can't wait until I finished backing up my hard drives and install Linux because you people really seem to understand what you're talking about :)
Code:

#include<iostream>

using namespace std;

int main()
{
float OneKiloMetre = 100000.00;
double OneMile = 182880;
float OneInch = 2.54;
float OneFoot = 12.48;
float OneMetre = 100.00;

cout<<"What would you like to convert to centimetres? ";
int TypeToBeConverted = 0;

cout<<"1.)Inches"<<endl;

cout<<"2.)Feet"<<endl;

cout<<"3.)Metres"<<endl;

cout<<"4.)Miles"<<endl;

cout<<"5.)Kilometres"<<endl;

cin>>TypeToBeConverted;


void ConversionTime();

float InchesConversion = 0;
float FeetConversion =0;
float KiloMetreConversion = 0;
float MileConversion = 0;
float MetreConversion = 0;
switch(TypeToBeConverted)
{

case 1:

cout<<"Enter how many Inches you want converted to centimetres: "<<endl;
cin>>InchesConversion;
cout<<"The conversion of "<<InchesConversion<<" inches to centimetres is ";
InchesConversion * OneInch = InchesConversion;
break;


case 2:
cout<<"Enter the number of feet you want to convert to centimetres: ";
cin>>FeetConversion;
cout<<"The conversion from "<<FeetConversion; " feet to centimetres returned "<<OneFoot * = FeetConversion;<<" centimetres;
break
case 3:
cout<<"Enter the number of metres you want to convert to centimetres: ";
cin<<MetreConversion;
cout<<"The conversion of "<<MetreConversion<<" metre/s to centimetres is "<<MetreConversion * = OneMetre;" cm's."
break

case 4:
cout<<"Enter the number of miles you want to convert to centimetres: ";
cin>>MileConversion;
cout<<"The conversion of "<<MileConversion<<" to centimetres is "<<MileConversion * = OneMile;" centimetres."
break

case 5:
cout<<"Enter the number of kilometres you want to convert to centimetres: ";
cin>>KiloMetreConversion;
cout<<"The conversion of "<<KiloMetreConversion<<" kilometres is "<<KiloMetreConversion * = OneMile<<" centimetres";
break
}

return (0);
}

InvisibleSniper.:Pengy:

Nylex 07-21-2005 02:18 PM

Quote:

Originally posted by InvisibleSniper
switch(TypeToBeConverted)
{

case 1:

cout<<"Enter how many Inches you want converted to centimetres: "<<endl;
cin>>InchesConversion;
cout<<"The conversion of "<<InchesConversion<<" inches to centimetres is ";
InchesConversion * OneInch = InchesConversion;
break;

There shouldn't be a semi-colon after " inches to centimetres is ". Also there is no need for the = sign. It should just be

Code:

cout << "The conversion of " << InchesConversion << " inches to centimetres is " << InchesConversion * OneInch;

elyk1212 07-21-2005 02:45 PM

Actually did that even compile?

InchesConversion * OneInch = InchesConversion;

If so, what would the assignment be? Interesting. Perhaps evaluated and thrown out.

lowpro2k3 07-21-2005 02:57 PM

Quote:

Originally posted by elyk1212
Actually did that even compile?

InchesConversion * OneInch = InchesConversion;

If so, what would the assignment be? Interesting. Perhaps evaluated and thrown out.

No, it doesnt compile. Theres at least 10 errors that I was about to fix but I dont have time (Im 2 days late securing my works slackware server :eek:)

Also take a look at the break statements - no semicolons.

Also, this line is there somewhere:

Code:

void ConversionTime();
That would be a valid function prototype - if it weren't in the main() function! That needs to be removed. I got pretty far but was having VC++ errors with cout's and floats/doubles??? Weird.

Quick question: is this legal C++:

Code:

float f1 = 42.651;
float f2 = 66.888;

cout << "value is: " << f1 * f2 << endl;

I was tired and rushing, but that was giving me a compile error so I had to quit after cleaning 90% of the code. Maybe I'll have time tonite, but I need to install tripwire,firewall,apache,etc.. on a server so I might not.

Nylex 07-21-2005 03:13 PM

Quote:

Originally posted by lowpro2k3
Quick question: is this legal C++:

Code:

float f1 = 42.651;
float f2 = 66.888;

cout << "value is: " << f1 * f2 << endl;

I was tired and rushing, but that was giving me a compile error so I had to quit after cleaning 90% of the code. Maybe I'll have time tonite, but I need to install tripwire,firewall,apache,etc.. on a server so I might not.

It compiles for me and works fine. I heard some compilers complain if you don't put f1 * f2 between parentheses.

elyk1212 07-21-2005 05:48 PM

Yes, all depends on the compiler. It may try to convert the f1 to ASCII char array, and try to output it before applying the '*' operator. This is solved, and is better written code by explicitly placing the parenthesis on this evaluation.

BETTER YET: Do you think you may have the need to use that result later in your code? If so, please feel free to use a variable to hold this:

Code:


float result = f1 * f2;

If you find yourself performing the same calculation more than once, it is much more efficient to keep the value for later use. This has the added bonus of avoiding compiler quirks with operator precedence.

lowpro2k3 07-21-2005 06:45 PM

OK I was trying to do something dumb in my tired state (cout << something *= somethingElse ...), so I made those fixes and heres the code. I only implemented 2/5 switch cases, and I didnt change any variable names (although i was very tempted) and tried to leave the code as much "as-is" as I could, while still showing you a few new things. Hope you enjoy, I tested this in VC++6.0, but it should work in any C++ compiler.

Code:

#include <iostream>
using namespace std;

int main()
{
        double  OneKiloMetre = 100000.00;
        double OneMile        = 182880;
        double  OneInch        = 2.54;
        double  OneFoot        = 12.48;
        double  OneMetre        = 100.00;

        int TypeToBeConverted = 0;

        cout<< "What would you like to convert to centimetres?\n"
                << "1.)Inches" << endl
                << "2.)Feet" << endl
                << "3.)Metres" << endl
                << "4.)Miles" << endl
                << "5.)Kilometres" << endl
                << "Enter your selection: ";
        cin >> TypeToBeConverted;


        // What are you trying to do below?
        // This is illegal in C++
        // Dont write the return type before a function call
        //        void ConversionTime();

        float InchesConversion = 0;
        float FeetConversion =0;
        float KiloMetreConversion = 0;
        float MileConversion = 0;
        float MetreConversion = 0;

        switch(TypeToBeConverted)
        {

        case 1:
                cout << "Inches to Centimeters..." << endl
                        << "Enter Inches: ";
                cin >>InchesConversion;

                // Your old conversion below:
                // InchesConversion * OneInch = InchesConversion;
                // I think you mean:
                // InchesConversion = OneInch * InchesConversion
                // Be careful with variable names!
                cout << InchesConversion << " inches is "
                        << InchesConversion * OneInch
                        << " centimeters\n";
                break;

        case 2:
                cout << "Feet to Centimeters..." << endl
                        << "Enter Feet: ";
                cin >> FeetConversion;

                cout << FeetConversion << " feet is "
                        << FeetConversion * OneFoot
                        << " centimeters\n";
                break;

        case 3:
                cout << "Not Implemented yet!" << endl;
                break;

        case 4:
                cout << "Not Implemented yet!" << endl;
                break;

        case 5:
                cout << "Not Implemented yet!" << endl;
                break;
        }

        return (0);
}


elyk1212 07-22-2005 01:45 AM

Just a programmers note, we usually declare named constants as to avoid magic numbers. For example: Will everyone remember what type 2 refers to without looking through much of your code? Probably not. anyhow that is really easy, just

do a

const int FEET_CONVERSION = 2;


and so on (outside of main is fine as global constants are OK). This helps make your code readable.


so inside your switch could be

case FEET_CONVERSION:
/* STUFF*/

break;

Makes life easier for you and anyone who dares modify the code.


All times are GMT -5. The time now is 07:39 AM.