【C++】1351 - Buying park tickets (exhaustive)

The ticket price of a certain park is: 8 yuan/person for adults and 3 yuan/person for children; a tourist group came to the park to play. There were adults and children in the group (both adults and children), and they spent a total of 40 yuan on tickets.
Please calculate the possible number of adults and children respectively, and count the results according to the rules from least to most for adults and from most to least for children.

Insert image description here

1. Analyze the problem

  1. Known: Adult tickets cost 8 yuan/ticket, children’s tickets cost 3 yuan/ticket; a total of 40 yuan was spent on tickets.
  2. Unknown: Number of adults and children.
  3. Relationships: Adults from least to most, children from most to least.

2. Define variables

Define variables as needed based on the known and unknown of the analysis.

3. Enter data

none.

4.Data calculation

4.1 Determine the scope of the problem: According to the requirements of the problem, determine the range of values ​​that need to be tried.

Adult tickets: at least 1, maximum (40-3)/8. Make sure there is a child ticket.
Child tickets: at least 1, maximum (40-8)/3. Make sure you have an adult ticket.

4.2 Use loops for exhaustive enumeration: Use loop structures (such as for loops) to traverse each value in the range.

i: Number of adult tickets.

for(int i=1;i<=(40-3)/8;i++){
    
    
	
	}

4.3 Bring the numerical value into the problem to try: Bring the current numerical value into the problem to determine whether the conditions of the problem are met.

j: The remaining money after purchasing adult tickets.

If j%3==0, it means that the remaining money can buy an integer number of children's tickets, which is in line with the meaning of the question.

//四、数据计算 
	for(int i=1;i<=(40-3)/8;i++){
    
    
		int j=40-8*i;
		if(j%3==0){
    
    
		}
		
	}
	

4.4 If the conditions are met, output the results or perform other operations. If the current value meets the conditions of the problem, you can output the value as the solution to the problem, or perform other operations.

//四、数据计算 
	for(int i=1;i<=(40-3)/8;i++){
    
    
		int j=40-8*i;
		if(j%3==0){
    
    
			//五、输出结果 
			cout<<i<<" "<<j/3;
		}
		
	}

4.5 Continue looping until all possible solutions are exhausted.

5. Output results

#include<iostream>
#include<iomanip>
using namespace std;
int main(){
    
    
	//一、分析问题
	//1. 已知:成人票 8 元 / 张,儿童票 3 元 / 张;共花了 40 元买门票。
	//2. 未知:成人和儿童的人数。
	//二、数据定义 
	//三、数据输入 
	//四、数据计算 
	for(int i=1;i<=(40-3)/8;i++){
    
    
		int j=40-8*i;
		if(j%3==0){
    
    
			//五、输出结果 
			cout<<i<<" "<<j/3;
		}
		
	}

	return 0;	
}

おすすめ

転載: blog.csdn.net/qq_39180358/article/details/135337404