C++程序,随机输入四个数字,组成不重复的三位数

原题目是“有1,2,3,4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

后增加了条件:输入4个数字,可重复相同数字

#include "pch.h"
#include <iostream>
#include <algorithm>
using namespace std;

//【模板类】实现——将得到的4个数字,组合成不含重复数字的3位数。
template<typename T>
void Karray(T& a,T& b,T& c,T& d) {
	T temp1=0, temp2=0, temp3=0, TEMP=0;//类型为T,随主函数参而变
	int temp_array[] = { a,b,c,d };
	int tem[24];//——
	int m = 0;//用于计数
	for (int i = 0; i < 4; i++) {				//first
		temp1 = temp_array[i];
		for (int j = 0; j < 4; j++) {			//second
			temp2 = temp_array[j];
			for (int k = 0; k < 4; k++) {		//thrid
				temp3 = temp_array[k];
				if (temp1 != temp2 && temp1 != temp3 && temp2 != temp3) {	//排除重复数字
					tem[m] = 100 * temp1 + 10 * temp2 + temp3;
					if (tem[m]<1000) {
						m += 1;
					}
				}
				
			}
		}

	}
	sort(tem, tem + m, less<int>());        //必须的,先排序,再删减
	int n = unique(tem, tem + m) - tem;     //删减
	cout <<"共:"<< n<<"个有效数字"<<endl;

	for(int i = 0; i < n; i++ ){
		cout << "四个输入数字自由组合的三位数,第" << i + 1 << "个:" << tem[i] << endl;
	}
}

int main() {
	int a, b, c, d;
	cout << "请输入四个十以内数字,回车符隔开:" << endl;
	cin >> a >> b >> c >> d;
	Karray(a, b, c, d);

	return 0;
}

《C++程序,随机输入四个数字,组成不重复的三位数》

《C++程序,随机输入四个数字,组成不重复的三位数》

    原文作者:Ry_Lawrence
    原文地址: https://blog.csdn.net/qq_25220319/article/details/102765460
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞