How to Display Percentages in C++

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.
Use quotation marks to help display percentages in C++.

A percentage is a ratio expressed as part of one hundred. It is written as a number followed by the percent sign (%). C++ classifies numbers with several different data types. One of them is an integer. Another is a float, which is used for decimal assignments and calculations. A double is a type that can also handle integer assignments, but it is more precise than a float. To display percentages in C++, cast the variables as floats or doubles. After the calculations are done, treat the percent sign as a string by enclosing it with quotations.

Advertisement

Step 1

Write a C++ file with the iostream header, namespace and int main().

Video of the Day

include using namespace std;

int main() {

Advertisement

Step 2

Create float variables. Given variables x, y and answer, the code is:

float x; float y; float answer;

Step 3

Instruct the user to input two numbers. As an example, write:

Advertisement

cout<<"Enter the first number : "; cin >> x; cout << "Enter the second number: "; cin >> y;

Advertisement

Step 4

Perform a percentage calculation and assign the result to answer. Write:

Advertisement

Step 5

Output the variables. After answer, add the percent sign and enclose it in quotations so that the compiler will treat it as a string. For instance, write:

cout << x << " over " << y << " is " << answer << "%" << endl;

Step 6

End the program with return 0 and a bracket. Compile and run it. A test program where x is 5 and y is 7 yields answer = 71.4826%.

Video of the Day

Advertisement

Advertisement

references & resources