C++: An Introduction - Part 4
ipastrano (91)

Hi guys, I don't even know if people are still reading this stuff, but here it is.

Changelog:

  • 3-1-2020: 5:09 - showed that comparison of floats is not always accurate

Ok, today I will show you 2 things:

  • Getting input from the user
  • Floating-point variables(they can hold decimals)

Getting input from the user

So by now I have showed you how to output and create variables. Now, this is great, but if you want to make a game or something, then you will probably need the user's input.

To do this, use this command:

cin >> var; //var is a variable name

So, cin is to input. (note that you also need #include <iostream> for this)
Note that cin won't say anything. It will just ask WHERE IS MY VALUE?!?!. To make your program more user-friendly, use cout to prompt the user like this:

int cal;
cout << "How many calories was your dinner? "
cin >> cal;

Output:
How many calories was your dinner? 500

Floating-Point Variables

So, you know how to use integer variables. But what if you need to hold a decimal, such as the cost of a computer, or a score on a test? This is where floating-point variables come in. Here are a few:

  • float - for average floating points.
  • double - for longer floating points.
  • long double - for REALLY long floating points.
    Use them in this manner:
float score;
cout << "What score did you get on the test? ";
cin >> score;
cout << "You got " << score << "% on the test! Great job!\n";//great job will print even if they got a bad score
  • Small note (credit to @Highwayman): When comparing floating point numbers, sometimes, there are errors. For example, 1.0 and 1.00 may not be the same to the compiler, or small numbers such as 0.000000000000001 and 0.00000000000000002 may be the same to the compiler. Use caution!
  • We have come to the end of this post, but I have a project for all of you:
  • Write a program that asks for the test scores of 3 students, and then prints them out nicely:
    Ex:
    What score did Student 1 get? 83
    What score did Student 2 get? 97
    What score did Student 3 get? 69

Student 1 got 83%
Student 2 got 97%
Student 3 got 69%

Comment a link to your programs below!

That's all folks!

(Jazzy music here)

You are viewing a single comment. View All