Search

2.10 — Chapter 2 comprehensive quiz

Quick Review

Integers are used for holding whole numbers. When using integers, keep an eye out for overflow and integer division problems. Use fixed-width integers instead of the variable size integers.

Floating point numbers are used for holding real numbers (which can have fractional components). When using floating point numbers, keep an eye out for precision issues, rounding errors, and comparison issues.

Boolean values hold only true and false. They do not have any major issues.

Char values are integers that can be interpreted as an ASCII value. When using chars, be careful not to mix up ASCII code values and numbers, and watch for overflow and integer division problems.

Use the const keyword to declare symbolic constants instead of #define. It’s safer.

Comprehensive quiz

Question 1

Why are symbolic constants usually a better choice than literal constants? Why are const symbolic constants usually a better choice than #defined symbolic constants?

Show Solution

Question 2

Pick the appropriate data type for a variable in each of the following situations. Be as specific as possible. If the answer is an integer, pick a specific integer type (e.g. int16_t) based on range. If the variable should be const, say so.

a) The age of the user (in years)
b) Whether the user wants color or not
c) pi (3.14159265)
d) The number of pages in a textbook
e) The price of a stock in dollars (to 2 decimal places)
f) How many times you’ve blinked since you were born (note: answer is in the millions)
g) A user selecting an option from a menu by letter
h) The year someone was born

Show Solution

Question 3

Write the following program: The user is asked to enter 2 floating point numbers (use doubles). The user is then asked to enter one of the following mathematical symbols: +, -, *, or /. The program computes the answer on the two numbers the user entered and prints the results. If the user enters an invalid symbol, the program should print nothing.

Example of program:

Enter a double value: 7
Enter a double value: 5
Enter one of the following: +, -, *, or /: *
7 * 5 is 35

Hint: You can check if the user has entered a plus symbol using an if statement, covered in section 2.6 -- Boolean values.

Show Solution

Question 4

This one is a little more challenging. Write a short program to simulate a ball being dropped off of a tower. To start, the user should be asked for the initial height of the tower in meters. Assume normal gravity (9.8 m/s2), and that the ball has no initial velocity (the ball is not moving to start). Have the program output the height of the ball above the ground after 0, 1, 2, 3, 4, and 5 seconds. The ball should not go underneath the ground (height 0).

Your program should include a header file named constants.h that includes a namespace called myConstants. In the myConstants namespace, define a symbolic constant to hold the value of gravity (9.8). See section 2.9 -- Symbolic constants and the const keyword for a reminder on how to do this.

Use a function to calculate the height of the ball after x seconds. The function can calculate how far the ball has fallen after x seconds using the following formula: distance fallen = gravity_constant * x_seconds2 / 2

Sample output:

Enter the initial height of the tower in meters: 100
At 0 seconds, the ball is at height: 100 meters
At 1 seconds, the ball is at height: 95.1 meters
At 2 seconds, the ball is at height: 80.4 meters
At 3 seconds, the ball is at height: 55.9 meters
At 4 seconds, the ball is at height: 21.6 meters
At 5 seconds, the ball is on the ground.

Note: Depending on the initial height, the ball may not reach the ground in 5 seconds -- that’s okay. We’ll improve this program once we’ve covered loops.
Note: The ^ symbol isn’t an exponent in C++. Implement the formula using multiplication instead of exponentiation.

Show Solution

3.1 -- Operator precedence and associativity
Index
2.9 -- Const, constexpr, and symbolic constants

314 comments to 2.10 — Chapter 2 comprehensive quiz

  • justAnotherConfusedStudent

    Hi Alex,

    I’m getting a strange error for my code I’ve written for #3. I’m currently using an online compiler (https://www.tutorialspoint.com/compile_cpp_online.php). My code is below:

    The error I’m getting when I compile is that in line 21, "ISO C++ forbids comparison between pointer and integer [-fpermissive]". This happens for every comparison within my if statement. Why is this happening? I can’t find syntax errors, and the online compiler doesn’t have a debugger.

  • Dear Mr teacher,

    I have a question:
    Everytime when I compile a file containing std::cout or std::cin it gives me "Error C2039: "cout" is no element of "std"".
    I tried to copy one of your programs but it still doesn’t work.
    What can I do?

    Thanks a lot.

    • Alex

      What compiler are you using? If you’re using a really old compiler, it may not have proper support for the std namespace.

      Also, make sure you’re including iostream, not iostream.h.

    • justAnotherConfusedStudent

      It seems like quite a few people have had issues with this too. Here’s a link to the stack overflow thread that I found:
      https://stackoverflow.com/questions/15359589/cout-is-not-a-member-of-std-cout-was-not-declared-in-this-scope

  • lnm

    what do u think about my code ? ( question 4 ) and correct them if necessary
    main.cpp:

    and constant&functionG.h

    • Alex

      You wrote a recursive solution, where function cal() calls itself. That’s clever. This will work as long as the initial height is reasonable, but your program may crash if the initial height is extremely large (and your function calls itself too many times). That’s not an issue for an academic program like this one though.

      Your program could use better variable names and some comments. Why is x named x instead of seconds? What is cal calculating? Other than that, it looks good.

  • Cat

    Hey there Alex! I am curious why it wouldn’t work for question 3 to do a separate bool function for the operators. I even tried this function as a header, and cannot get it to recognize the actual operation. every answer comes back as ‘1’. Does bool only compare values and variables? hence why I couldn’t just have it return the value of double1 + double2 if char is ‘+’?

    • Alex

      I’m not sure I follow you. Boolean values can only be set to true (1) or false (0). So if you’re trying to return double1 + double2 as a boolean, it’ll always evaluate to boolean true unless double1 + double2 = 0.

      • Cat

        Sounds like you do follow! And yea I had actually realized the issue using bool for that purpose. I was hoping to just separate dealing with the chars from cout/cin expressions for readability.

  • AMG

    Alex,
    Question 3:
    From your answer, function getDouble() does not print "Enter a second double value". So I would suggest either to remove word "second", or in assignment also ask "Enter a first double value".
    Question 4:
    From your answer: calculateAndPrintHeight(initialHeight, 0). I don’t think we should use literal constant (even in very trivial scenario), otherwise I would modify answer for Question 1.
    Questions 3 and 4:
    I thought type "double" is for precision, so float should be sufficient in these questions. Why do use double?
    Also in question 4, arithmetic statement has int and double types together. Would you advise to cast types? Or in now days it’s not so important.
    Thank you,
    Alex

    • Alex

      Thanks for the feedback:
      Question 3: Fixed. Thanks for pointing out the inconsistency.
      Question 4: Why not? Normally I’d recommend using a loop here, but we haven’t covered loops yet.
      There’s almost no reason to use “float” unless memory is at a premium. It’s definitely not in this case, so you might as well favor high precision since you can.
      If you mix a double and an int in an arithmetic statement, the compile will implicit convert the int to a double. We cover this process in more detail in chapter 4. There’s no need to be explicit about the conversion.

  • Hmm, for some reason the backslash n characters only appear as n in the code listings and comments.

  • Hello again Alex and other commenters,
    This eventually became my idea for question 4 (ball dropped from tower), this took far longer than I care to admit to 😉 because the last time I dealt with this type of formula and conversion to an algorithm was at college and computer math classes.

    I took a slightly different approach to solving this problem, in my forward declaration section starting at line 9, I just typed a load of comments one below the other that defined the steps I needed to take, converted those into function prototypes, and from there created function definitions below the main() section and finally built out the main section, I doubt that this is a correct procedure but it seemed to work for me, what are your thoughts on this approach to solving the problem.

    This was my listing which pretty much paraphrases your solution:-
    constants.h

    And main.cpp

    It seems to build an run fine, I also tried to keep it so it used items that had been already mentioned in previous chapters
    Jon.

  • Hello again

    This was my take on question 3, is there a better way to format the output of my print_result()? I think this looks a bit of a mess

    • Alex

      Looks fine to me. 🙂 You could separate out each individual variable if you wanted:

      I’m not sure that’s any better.

      • Thanks for the reply,
        I’ll leave it as it is, its probably just me getting used to the differences between php/html and C++. Also this is formatted for console output, a completely different medium for me.

  • Losus

    Hello!
    Your tutorials are amazing. I have been studying in your site for 2 weeks now.
    I was wondering if you could look at my code and give me feedback about how my comments are doing :).
    If you notice something different than that please feel free to point that out.
    My English is not very good hope i can explain myself.
    main.cpp

    I used a seperate function to calculate distanceFallen because i thought i can use it later if i decide to upgrade this code.
    I didn’t include constants.h. It is the same as yours.

    • Alex

      A few thoughts:
      1) It’s better to put your function comments before the function rather than inside the function.
      2) Some of your function comments could be shortened:

      // We will calculate the current height of the ball
      // by substracting distance fallen from initial height.

      Could just be
      // Calculates the current height of the ball at time ‘time’

      That tells the user what the function is used for. The user can look at the code to determine how (if they care), since there’s nothing complicated going on here

      3) A minor error:
      // We will calculate how many meters the ball has fallen
      // by using the time given at compile-time and the Physics formula.

      Time is being set at runtime, not compile time.

      Other than that, looks better than 99% of what I see. 🙂

      • Losus

        Thank you so much for your reply.

        1) Using comments before functions instead of inside them totally make sense and i see that now.

        2) I understand why i should shorhen those comments. "Further explanation about how the code works not required"

        3) I couldn’t understand this. I gave the value of time to before compiling calculateAndPrintHeight() function. If this doesn’t make time
           value compile-time value what does. Perhaps myConstants::gravity was set in compile-time. If i am somewhat completely wrong in this
           assumptions, please correct me. I don’t want to go on without understanding this.

        If you could enlighten me i would be so happy.
        Btw i love the fact that you still take care of this site. You are a good tutor.

        • Alex

          myConstants::gravity is a compile-time constant, as you suggest.

          When you call calculateAndPrintHeight(initialHeight, 3); the 3 is also a compile-time constant (literal).

          However, for the function calculateAndPrintHeight(double initialHeight, int time) itself, time is not a compile-time constant. The compiler doesn’t know in advance what values time is going to have. This is determined at runtime.

  • Matt

    I was wondering if I could get some feedback on how to make my code prettier for the ball drop. I have a program that works, but it seems a bit clunky, and I wasn’t sure what I could do to make it nicer.

    • Alex

      I think the main way I’d clean up your code is to move the body of your while loop into a function. That will make your main() shorter and more managable.

  • acm1264

    Hello! I was wondering if I could get some pointers on how to improve my code. It functions properly, but did I make things too jumbled together?

    • Alex

      Your code isn’t bad. There are a few minor improvements you could make:
      1) newHeight does both calculation and printing, which violates the functions should do one thing rule.
      2) In main() you’re assigning the return values to variables and never using them. This is unnecessary. Just call the function and let the return value go ignored (don’t assign it to anything).

  • the functions and how to manipulate them. How to only use one function in int main while there were many outside it

  • Coach. I tried to understand question 4 but I still cannot grasp it.

  • Thank you for your comments. I actually realized it. I created a new one: (By the way, How can I send my program with the colors??)

    #include "stdafx.h"
    #include <iostream>
    double firstnumber()
    {
        double x;
        std::cout << "enter your first number" << std::endl;
        std::cin >> x;
        std::cout << "your first number is:" << x << std::endl;
        return x;
    }

    double secondnumber()
    {
        double y;
        std::cout << "enter your second number" << std::endl;
        std::cin >> y;
        std::cout << "your second number is:" << y << std::endl;
        return y;
    }

    char ChooseOperator()
    {
        char get;
        std::cout << "Enter a symbol: + - / *" << std::endl;
        std::cin >> get;
        return get;
    }

    void TheAnswer(char get, double x,double y)
    {
        if (get == ‘+’)
        {
            std::cout << x << "+" << y << "=" << x + y<<std::endl;
        }
        if (get == ‘-‘)
        {
            std::cout << x << "-" << y << "=" << x - y;
        }
        if (get == ‘*’)
        {
            std::cout << x << "*" << y << "=" << x*y<<std::endl;
        }
        if (get == ‘/’)
        {
            std::cout << x << "/" << y << "=" << x / y<<std::endl;
        }
    }

    int main()
    {
        double a = firstnumber();
        double b = secondnumber();
        char c= ChooseOperator();
        TheAnswer(c,a,b);
        return 0;
    }

  • Thank you for answering me last time. I did the question 3 and I would like feedbacks to improve my work. Sorry I don’t know how to send with the colors

    // ConsoleApplication2.cpp : Defines the entry point for the console application.
    // this program ask the user to take 2 integers to find their sum or their difference, product or the quotient of the two.

    #include "stdafx.h"
    #include <iostream>

    int main()
    {
        double x, y;
        std::cout << "Please enter two numbers to addition, substract, multiply or divide based on the symbol you will choose later" << std::endl;
        std::cin >> x;
        std::cout << "Your numb 1 is: " << x << std::endl;
        std::cin >> y;
        std::cout << "Your numb 2 is: " << y << std::endl;
        char a;//character a will be + or - or * or /.
        std::cout << "Please enter a symbol.\n + is for addition.\n - is for substraction.\n * is for multiplication.\n / is for division." << std::endl;
        std::cin >> a;
        double function();//using if for the different cases.m
        {
            if (a == ‘/’)
            {
                std::cout << "the division of numb 1 by numb 2 is:" << x / y << std::endl;
            }
            if (a == ‘+’)
            {
                std::cout << "The addition of 2 numb is:" << x + y << std::endl;
            }
            if (a == ‘-‘)
            {
                std::cout << " numb 1 minus numb 2 is:" << x - y << std::endl;
            }
            if (a == ‘*’)
            {
                std::cout << "The multiplication of te 2 numb is:" << x*y << std::endl;
            }
            if (a != ‘/’ && a != ‘*’ && a != ‘-‘ && a != ‘+’)
            {
                std::cout << "The symbol you entered is not among the 4 types described above" << std::endl;//rather than print nothing I wanted to print this
                                                                                                            //so that the user knows he made a mistake.
            }
            return a;
        }
        return 0;
    }

    • Alex

      This program doesn’t make any sense to me. It looks like you’re trying to define a nested function (which C++ doesn’t support), but you’ve done it incorrectly so the body of the function is actually part of main().

  • Chris

    Thank you for these tutorials.  They have been amazing.  

    Can you take a look at this?  I know it works, but is there a better way or any problems I haven’t considered (minus user input error)?

    Thanks!

    • Alex

      In performFunction(), there’s no point in storing the answer in variable “answer” since all you do is return it. You might as well return the answer directly (e.g. return x + y).

      Also, you’re probably better off using ‘\n’ instead of std::endl.

      Outside of that, this looks great.

  • Abheet

    I think there is a little correction needed in the Solution of Question 2.

    You typed in :

    "d) Since books can often have more than 255 pages but probably never have more than 32,767 pages, int16t is a good choice here."

    Here you spelled "int16_t" wrong.

    Thanks for these lessons. They help A LOT!

  • Jim Smith

    I added a little function that calculates the speed of the ball.

  • Jerin

    is this correct? is there any issue if i do like this?

  • Carl Carver

    Alex, this course is brilliant.

    Programming, at least to the newcomer, appears to be one of those high level exercises which you find out later isn’t as hard as it’s made to sound! I was just about to post a question, as I’d been stumped on solving question 3, however, in typing the question up the answer presented it’s self to me! 🙂

    You’re really demystifying at lot of this for me! I Just wanted to let you know how much this is helping me and how greatly appreciated your efforts are. 🙂

    Carl

  • Said

    This is what I got

  • Liam F

    This was the code I used to make the program count every second untill the ball hits the floor.

  • felipe

    I have a question that has not really been totally answered before.

    Is there a c++ library that lets you pass a math operator as a variable? ex,

    I know this can be done locally but I was wondering if there was a library that did it.

    Example code just in case im not specific enought:

    Thanks.

    • Alex

      I’m not sure I understand what you’re asking. When you say “library”, what do you mean by that in this context?

    • Carl Carver

      I just made my own:

  • akde

    Hi Alex

    Thanks for the great material.

    I have the following code

    But I get the following errors
    ‘gravity’: undeclared identifier    
    ‘myConstants’: is not a class or namespace name

  • James Ray

    Hi Alex,

    I like how you have the solution straight after the question. It saves having to scroll up and down to check the answer once you’ve done each question.

  • Aakash

    Hi Alex,
    Can you tell me how to call c# functions in c++ so I can use convert.to string() or convert.toint() directly in c++ for my UWP calculator program. I want to convert the user input from textbox(string) to double. I am using Visual Studio 2015 and didn’t know how to achieve this. I don’t want to write my program in c#.

    • Alex

      I don’t know much about C# interoperability, so I can’t be of assistance here. I’m sure someone has asked this question on Stack Overflow, so many a Google query will surface something useful.

  • Ben

    Hi,

    Great turotials 🙂 i’m learning alot.

    Just wondering why you

    rather than calling the function to print the height and passing the values on that way?

    Is either approach ok or is there a specific reason why returning something is better?

    thanks,
    Ben

    • Alex

      You wouldn’t expect a calculate function to print values. So the calculate function only does the calculation, and if the caller wants to print the results of the calculation, they can do so themselves.

      Otherwise you end up with functions that are overly-specific (what happens if you want to do a calculation but not print the results? Now you have to modify the function, at which point you risk introducing bugs).

  • Rhys

    Question 4. I get the error ‘myConstants’ has not been declared

    main.cpp

    constants.cpp

    constants.h

  • Dan

    Thank you so much for the content you provide, Alex. =)

  • Nick

    Hi Alex, this is what I did just now for question 3.
    In your opinion, is this good enough? I hope I can learn your method of writing code since you can write it simple enough for everyone to understand.

    #include <iostream>
    using namespace std;

    void program(double x, char z, double y){
        if (z == ‘+’)
        cout << x << "+" << y << "is" << x+y << endl;
        else if (z == ‘-‘)
        cout << x << "-" << y << "is" << x-y << endl;
        else if (z == ‘*’)
        cout << x << "*" << y << "is" << x*y << endl;
        else if (z == ‘/’)
        cout << x << "/" << y << "is" << x/y << endl;

    }
    int main()
    {
    cout << "Enter a double value: " ;
    double x;
    cin >> x;
    cout << "Enter a second double value: " ;
    double y;
    cin >> y;
    cout << "Enter one of the following: +, -, *, or /: ";
    char z;
    cin >> z;
    program(x,z,y);

    return 0;
    }

  • Zhengxiu

    Thank you for the helpful quiz.
    When I tried to use
    double distanceFallen = constants::gravity * (sec ^ 2) / 2;
    (line 27)
    Something unexpected happened.
    Can you please tell me why?
    And in the answer you combine the calculation function and the printing function in a whole new function.
    Is it recommended to do so? Why?

    • Alex

      The ^ symbol isn’t an exponent in C++. I’ve added a note to the lesson.

      > And in the answer you combine the calculation function and the printing function in a whole new function. Is it recommended to do so? Why?

      I did so because it reduces the amount of redundant code. It’s not necessary, but I thought it was better than not.

  • Rafael

    I want to see if the way I built the code for Question 4 is viable or if I incremented some bad habits to it, thank you in advance:

    "constants.h"

    "main.cpp"

    • Alex

      It’s syntactically okay. But it’s a little weird that function check() prints something to the console in the else case, and not in the if case. It would be better if check() printed in both cases (or neither). Plus it could use a better name, what are you checking?

      • Rafael

        The if’s (inside main) would have their time changed and then call the boolean "check()" which will determine if at that time the ball is on the ground (and print out exactly at what time it got there)* or not (and how much distance must be covered to reach the ground)
        *Note: The expression I used in the above program is incorrect since I forgot the square root in what I defined to be

  • saeid

    i complete my code in question 4 for any height and any seconds longs to reach ball the ground. is it good coding method or not ? :

    • Alex

      The program structure and data flow looks good. However, your function names could be improved:
      * initialHeight() could be renamed getInitialHeight() or getInitialHeightFromUser().
      * distance could be renamed distanceFromGround()
      * results could be renamed printCurrentHeight()

      This makes it clearer what they are doing, and makes the logic of main() easier to understand.

  • David

    I am trying to make a distance conversion program, but I am having difficulty with one of the functions. In the function "calculateValue" the compiler says that the varible newValue is undefined even though I did that in the lines just before. Is there something I’m missing?

    • Alex

      Variables can’t be declared in the statement part of an if or else statement. Move the variable declaration above the if statement, or use the conditional operator instead:

      Like this:

      Or this:

  • Matt

    Question: Comparing your solution to the one I came up with (below), you combined “calculate ball height” and “print ball height” into a “calculate and print” function. Then you split the “calculate and print” function into two individual functions. While I understand that this cleans up main(), wouldn’t this get really out of hand if, say, we had 3+ tasks we need to perform? [main() would have to call task1task2task3 function, then that would call task1task2 function + task3 function, then task1task2 function would call individual task1 and task2 functions. You see where I’m going with that I hope… I guess my question is are the extra functions necessary, is “repeating yourself” in main() like I did a bad idea?

    The following is what I came up with for the ball drop problem.  I wanted to experiment with the "if / else" functionality a bit, so I made it say "you haven’t dropped the ball yet" for time = 0,  "…second" for time = 1 second, and "…seconds" for time >= 2 seconds.  

    I had some trouble embedding multiple if/else inside each other and had to resort to trial and error to figure it out.  This took a decent amount of time.  I hope there’s a better way to do this - I might have gotten ahead of myself there.

    At the bottom, commented out, you can see my outline that I made before writing the program.  Worked out pretty well!

    • Alex

      Repeating yourself should be avoided if possible, but not to the point of making your code harder to read or understand. There’s no problem calling calculate and print multiple times.

      We talk more about if/else in chapter 4 (as well as blocks, which you should definitely be using with nested if statements). For what it’s worth, you can remove the if (time == 1) case in function printBallElevation() -- it’s already handled by the subsequent case.

  • Coovi

    The code

  • David

    I can’t seem to figure out why my code is not working. It is different from the answer, but in my head I thought it would still work.

    By the way, awesome tutorials! Thank you!

    Also I misspelled “height” haha

    • Alex

      From inspection, I see a couple of issues (there may be others). First, function main() has a parameter, and it shouldn’t. Second, getInitialHight() is returning towerHight, but main() never does anything with it, so it’s discarded. You probably meant to assign this value to ballHight (which should be a local variable, not a function parameter).

  • Ramon Bijl

    Is it bad that I didn’t know the answer on question 4? I only succeeded in the header file part.

    (I do understand the code in the answer)

    • Alex

      When you’re learning, you’re not always going to get everything correct. That’s why I provide answers, so you can either compare your solutions against mine, or in the case where you can’t get to a solution on your own, you can look at mine and at least understand what it’s doing.

      As long as you feel like you have a good understanding of what the solution is doing, you’ll probably be fine.

  • Brad

    Thanks so much for these tutorials! That last challenge gave me the kick I needed to make sure I become more intimate with the use of functions instead of trying to fit all my code into main() 😛

  • Lusis

    #include <iostream>
    #include "stdafx.h"
    #include "constant.h"

    double getInitialHeight()
    {
        std::cout << "Enter the height of the tower in meters: ";
        double initialHeight;
        std::cin >> initialHeight;
        return initialHeight;
    }

    double calculateHeight(double initialHeight, int seconds)
    {
        double distanceFallen = (myConstants::gravity * seconds * seconds) / 2;
            double currentHeight = initialHeight - distanceFallen;
            return currentHeight;
    }
    void print(double initialHeight, int seconds)
    {
        initialHeight = calculateHeight(initialHeight, seconds);
        if (initialHeight > 0.0)
            std::cout << "At " << seconds << " seconds height is " << initialHeight << "  meters" << std::endl;
        else
            std::cout << "At " << seconds << " seconds, ball has reached ground" << std::endl;
    }

    int main()
    {
        const double initialHeight = getInitialHeight();

        print(initialHeight, 0);
        print(initialHeight, 1);
        print(initialHeight, 2);
        print(initialHeight, 3);
        print(initialHeight, 4);
        print(initialHeight, 5);

        return 0;
    }

    I made it a bit shorter. Is that right?

  • Afonso Urbano

    I have some background in coding (though not C or C++) so i have a fundamental understanding on loops. Here is the code I wrote for question 4:

    Do you think that there is anything I should be doing different?
    Thanks for the amazing tutorial by the way!

    • Alex

      The only thing I’d advise is giving metersFallen() a better name, since it prints a value, not just calculates one. Otherwise, looks great.

  • Christopher

    That last question made me want to punch my computer screen a little bit :3

  • Theo

    Hey Alex,
    Tried to do the exercise 3. I get no debug errors but then again the program just always prints 1 🙂 So where did I go wrong? I thought it would work if I used bool with the same reasoning as the prime numbers exercise.

    void writeAnswer(int x)
    {
        std::cout << "The answer is " << x << std::endl;
    }

    int main()
    {
    using namespace std;

    cout << "Please enter a  decimal number: " << endl;
    double x;
    cin >> x;

    cout << "Please enter a second decimal number: " << endl;
    double y;
    cin >> y;

    cout << "Please enter an appropriate symbol (+, -, /, *): " << endl;
    char z;
    cin >> z;

    bool symbol(false);

    if (z = ‘+’)
        symbol = true;
    else if (z = ‘-‘)
        symbol = true;
    else if (z = ‘*’)
        symbol = true;
    else if (z = ‘/’)
        symbol = true;

    if (true)
    writeAnswer(x + y || x - y || x * y || x / y);

        else
            std::cout << "" << std::endl;

        return 0;
    }

    • Alex

      There’s a couple of issues here:
      1) You’re using operator= to do comparison instead of operator==. Operator= is for assignment, operator== is for equivalence comparisons.
      2) if (true) always evaluates to true. You probably meant if (symbol).
      3) Your writeAnswer argument doesn’t make sense. With the primes example, a number either is prime or isn’t (boolean). However, with symbol, there are more than two choices, so using a bool here isn’t appropriate. You should probably do something like this:

  • Nick

    My interpretaion of this programm.

  • Philip

    The tutorial has been great so far.

    Question 4 has overwhelmed me completely for over a week, however. I have no idea how the thought process works to end up with anything close to the solution, even after reading the chapter many times over. Question 3 I managed to complete in just a few minutes (syntax and typo problems mostly). I can read and understand the solution easily enough - but the journey of figuring it out has knotted my brain in such unfathomable ways. Was it meant to be hard?

    • Alex

      Yes, that’s why it says, “This one is a little more challenging.” 🙂

      The process of trial and error and discovery is valuable, even if you don’t get to a solution yourself.

  • Professzore

    Hi Developers,
    I can’t see any code here with an example of pre-check for devide by zero…

    Here is my attempt for Question 3:

    • Professzore

      A bug:
      (true and false)

    • Alex

      Yup, ideally you should definitely be checking for division by 0, but at this point in the tutorials we haven’t covered operator&&, so I wouldn’t expect people to know how to use it. We’ll cover more about error handling in future chapters.

  • ihowa

    sorry for question three i solved the problem with a different method but my division operation isnt working as planned. can someone pls tell me why

  • functionLover

    i think it’s better style to write the code like this:

    double calculateHeight(const double gravity, double initialHeight, int seconds)

  • Rehman Ali

    can anyone please explain what is i++ or ++i in c++??
    And for what purpose they are used?

  • sehyun

    what is ‘-nan(ind)’?? It’s the result when there is inappropriate operator.

    • Alex

      NAN means “not a number”, and IND means the NAN is indefinite. You can also get this when you take the sqrt of a negative number, or try to add positive and negative infinity.

  • Darren

    I like

    on my chips (score out-of-ten).

  • neo

    I tried to find a way to allow the user to input their own choice of seconds for the ball to drop. Are there any improvements I can make?

  • hi.
    i write question 4 for any tower height and any time taken to reach the ground :

    and this is constants.h file contains :

    what u think ????

  • joe

    I am having a bit of trouble understanding what to use and how to use fixed-width integers and floating point numbers.

    For shits and giggles I was messing with one of the quizzes you gave earlier about the tower drop.  I was going to take it to a whole new level of stupidity in line with my nature by calculating something beyond my abilities.  Like finding out how far a projectile will travel if fired from a given angle at a given speed as well as its speed, altitude and angle at any given second during its flight.

    This is the final iteration of my code and it works just fine though it gives me an unexpected series of numbers and letters.  

    That last run gave me a return of 00fc14c9

    Am I not giving my code enough memory to hold the number, or am I messing up somewhere?

    • Alex

      You’re messing up in a couple of places. 🙂 First, you’re calling pSin(x, y), which is fine, but you’re not doing anything with the return value (like printing it). Second, in your std::cout statement, you’re printing pSin instead of the results of a function call to pSin(x, y). pSin apparently lives at memory address 00fc14c9, which is why it printed that value.

      Finally, it’s not good practice to precede your function names with a p prefix. What does p even stand for?

      • joe

        I realized after I posted that I should have turned pSin into a void type and print from there, so that problem was solved.  I am still unable to get an answer along the lines of what I am expecting.

        The p prefix was just a way for me to denote SINE and ARCSINE for when I got that far.  I can rework it if necessary.  

        I am unsure though if I am using the correct types.  I am expecting with the division of the hypotenuse and opposite side to give me a decimal number.  Such as if I were to input Opposite-1 / Hypotenuse-1.414 it would be .707.  then I would sin(.707) to come up with 45 degrees.  of course, how I would print out the degree is still something I am trying to figure out.  But I need to ensure the type I am inputing will hold the decimals and calculate accordingly.  

        I know the numbers will be exceptionally large.  I am curious if it would matter if I were to make the types cut those numbers off on purpose so as not to overtax the equation.  Because I would not need the numbers beyond a certain point, I would just go ahead and chop them with the type.  Would this be a bad idea.  If not, what would you suggest?

        It is an overly complicated and near ridiculous endeavor for me to attempt at this point, but it is the way I learn at times.

        • joe

          I think I figured it out.

          It is now giving me my numbers with decimal points

          • joe

            There is something interesting I stumbled upon when realize my math is off.  I attempted to input only one parameter to SIN in main.  Then with VOID SIN I tried to remove the LONG DOUBLE Y and swap out the z with x in the equation.  Removing z altogether.  But now Im getting :

            Error    1    error C2556: ‘void sin(long double)’ : overloaded function differs only by return type from ‘long double sin(long double) throw()’    e:\c++\helloworld\helloworld\helloworld.cpp    12    1    HelloWorld

            If I return two parameters to void sin, it works, but one parameter will not.

            • Alex

              You’re inadvertently discovering function overloading, where a function can have the same name if it has different parameters. This is discussed in more detail in chapter 7. In the meantime, you can work around this by ensuring your functions all have different names.

            • joe

              I figured it out.  Damn, this is hard, and fun as hell at the same time.

        • Alex

          Trying to do something at (or slightly beyond) your current capabilities is a great way to learn.

          A couple of additional thoughts: you don’t need to have pSin return a void and print the value from there. pSin can return a value and main can use std::cout to print it if the value being returned is a fundamental type.

          I’m glad you discovered the double data type. I was going to additionally suggest you use it, but you already are. 🙂

          • joe

            How would I return the value from the function to use it in another function?

            You said earlier

            "you’re not doing anything with the return value (like printing it). Second, in your std::cout statement, you’re printing pSin instead of the results of a function call to pSin(x, y)."

            In my code, I thought I was printing out the value since there was a return originally.  But it was not printing.  How am I to be sure it returned the value for me to print, or reuse?

            Oh, here is my revised void, which I can convert into a returnable type once I know how to.

            Thank you so much Alex, you are a great help.

            • Alex

  • J3ANP3T3R

    1.) What are the disadvantages of using Double rather than Float when for example accepting a numerical value denoting money (which often only requires 2 decimal places and so should be float) ?

    2.) can i use some sort of macros for converting strings into c++ statements ? like in visual foxpro where we can use & to denote a macro variable i can concat numVar1 + chosenOperator + numVar2 into a string dynaCommand then execute it in one line as &dynaCommand which would then be translated into a statement. example numVar1 = 4 numVar2 = 7 operator = ‘*’ to 4 * 7 and i can use it in nResult = &dynaCommand and will accept it as statement and not display an error ? sometimes i use macro to trim codes.

    • Alex

      1) Two thoughts here: First, floats may not be able to even hold decimal places. Consider a large value: 9876542.11. This value is just short of $10 million, but probably won’t fit in a float because there are too many significant digits. Second, because floats have less precision, any rounding errors they accumulate will be more significant than with a double (e.g. a double may incur a rounding error at the 8th decimal place whereas a float may incur a rounding error for the same number at the 2nd decimal place). The only real disadvantage of using a double over a float is that it takes more memory -- which generally won’t be a problem unless you’re dealing with massive quantities of numbers.

      2) There are ways to convert strings into integers, but it’s not easy. I cover this topic in chapter 13.

  • Alex

    So, I went ahead and took question 4 a little bit further. I made it loop while the height is greater than the ground(defined in Constants.h as 0). That way, it would just keep printing the position each second until the ball struck the ground. The following code is the program. Am I doing anything incorrectly?

    Output looks like this:

    • Alex

      Generally looks good. A couple of minor quibbles:
      1) Your variable names inside calcPosition aren’t very clear (why is seconds squared?), what does the c in cposition mean?
      2) You shouldn’t use system(“pause”), as it’s not standard C++. Use this instead:

      • Alex

        Thanks for the reply. I fixed the system("pause").

        I squared the seconds because the formula squares the seconds. cposition = current position.

        Should I be more clear and type out currentPosition instead of cposition?

        • Alex

          Yes, _I_ know why you squared seconds, but naming your variable seconds implies it’s going to hold the base number of seconds, not a squared value. secondsSquared might be a better name.

          A ‘c’ prefix on a variable could mean anything -- current, class, char, etc… Better to be more descriptive with your names. If you want to shortcut “current” to reduce typing, you can use “curPosition”.

  • Nyap

    for h on question 2, does const int16_t also count?

    • Nyap

      also, here’s my code for number 3:
      http://pastebin.com/47uHKias
      looking at the "solution" it’s pretty much the same just not refactored as much
      I’m not going to even bother with question 4 because I don’t even know what inital velocity is

      • Alex

        initial velocity is the ball’s initial speed. So no initial velocity simply means the ball starts in a stationary position (not moving).

    • Alex

      You could certainly make an argument that birthday shouldn’t be changed once set (after all, you can only be born once). But what if someone made a mistake entering it and needed to update the date? If it was const, they couldn’t do that. On that basis, I’d probably choose non-const.

      • Nyap

        ok, question 4 done!

        constants.h:

        main.cpp:

        that was actually quite fun 😀

        edit: hmm, actually, there’s a bug:
        At 0 seconds, the ball is at height: 999999
        At 1 seconds, the ball is at height: 999999
        At 2 seconds, the ball is at height: 999994.1
        At 3 seconds, the ball is at height: 999974.5
        At 4 seconds, the ball is at height: 999930.4
        The ball should have started moving at 1 seconds
        I need to fix that

        • Nyap

          fixed, had to make changes to fall():

  • Robbie

    Hi Alex, I’ve run into a massive problem, I defined gravity in the header file as a double (obviously 9.8) but when I use the constant in the formula (Y = Initial height - (Initial Velocity * Time + gravity/2 * time^2 I get
    #compiler error "myConstants::Gravity expression must have integral or unscoped enum type"

    (This actually doesn’t shop up it is just underlined in red)

    and then
    #compiler error " ‘^’illegal, left operand has type ‘double’ when I try to do time^2.

    I tried timee2 but that doesn’t work and gravity works if i define it as const int, but then it will be rounded up to 10 and will not be correct!

    Help Please.

  • Jester Arcas

    You said on question 3 to have boolean type but you didn’t use it. This is my code.

  • Walter

    I decided to keep track till the object fell to the ground. No guarantee the person would enter a distance that would be done within 5 seconds.  It wasn’t till I looked at the solution you provided that you capped it off at 5 seconds. That would have been easier (especially since I haven’t looked at recursion in over 20 years!)

  • trebor

    I have no question so stop reading if you don’t have time.

    Thank you Alex for this awesome tutorial, I’ve been following it from the first chapter. It took me around 20 minutes by section. I have some experience programing but there are many "little" things that I didn’t know.

    I’ll just try to paste my code in here. I used a loop because I didn’t realize that creating a function that prints with a conditional could make things easier, just like you did.

  • kylix

    Please help! why is this giving wrong answers 🙁 I can’t use const because my dev c++ doesn’t recognize both #include<constant.h> and const 🙁