Topic 1040: [Introduction to Programming] Printing of real numbers

A real number, float range

Output format

Output 3 lines, the first line prints the input number once, the second line prints it twice, and the third line prints it three times. On the second and third lines, separate numbers on the same line with spaces. Real numbers are output in "6.2f" format.

Sample input

copy

0.618

Sample output

copy

  0.62
  0.62   0.62
  0.62   0.62   0.6

Observing the output, we found that the first line outputs 1, the second line outputs 2, and the third line outputs 3:

Use a 3X3 double-layer for loop . The range of local variable i is 1~3 : the outer layer represents the row number, and the inner layer represents the number of outputs.

The outer statement is to set the local variable cnt=0 . It is a bit like finding a prime number and initializing the Boolean value of isPrime.

..>But this is not the best way,

method 1:

//实数的打印
#include<iostream>
using namespace std;

int main() {
	float num;
	cin >> num;
	int cnt = 1;  //计数仔上线 初始为1表示:第1行输出1个      第2行输出2个
	for (int j = 1; j <= 3; j++) {   //一共输出3次
		cnt = 0;
		for (int i = 1; i <= 3; i++) {  //每一行输出对应的个数
			if (cnt == j && cnt != 3) {  //第三次不endl跳行
				cout << endl;
				break;
			}
			printf("%6.2f ", num);       //专业四舍五入-留两位
			++cnt;   //自增1 表示本行输出1个num
		}
	}

	return 0;
}

Method 2:

Some experts may think that counting cnt is too troublesome, so just use i==j to judge - the number of outputs is the number of rows, right? Yes.

As for the difference between break and continue:

The break` statement is used to completely terminate the execution of the inner loop and continue the outer loop .

The `continue` statement is used to skip the remaining code of this inner loop and proceed directly to the next iteration of the inner loop .

; And after we judge that it is satisfied, we no longer need to output in the current line, so we completely jump out of the inner loop and proceed to the next outer loop.

//实数的打印
#include<iostream>
#include<iomanip>
using namespace std;

int main() {
	float num;
	cin >> num;

	for (int j = 1; j <= 3; j++) {   //一共输出3次
		for (int i = 1; i <= j; i++) {  //每一行输出对应的个数
			printf("%6.2f ", num);
			if (i == j) {
					cout << endl;
					break;
			}
		}
	}

	return 0;
}

Guess you like

Origin blog.csdn.net/qq_63999224/article/details/132364806