1 如何读入未知个参数 A: while(cin >> a......)
2 不能把max当作参数命名
3 max时候记得用algorithm
444444444最重要的 if 和 else if是互斥结构!!!!!!!所以完全可以把&& b!=c 等条件去掉。
#include <iostream>
#include <algorithm>
using namespace std;
int main (){
double a , b, c;
while(cin >>a >>b >>c){
double max_it = max(a,max(b,c));
double others = a + b + c - max_it;
if(max_it < others){
if(a == b && b==c) cout << "Equilateral triangle!";
else if ((a==b && b!= c)||(b == c && c!= a)||(a==c && c!= b)) cout <<"Isosceles triangle!";
else cout << "Ordinary triangle!";
}
else cout << "Not a triangle!";
cout <<endl;
}
return 0;
}
下面是一些输入复数个参数的例子
使用建议:
方法1最适合读取未知数量的数字
方法2适合有明确结束标志的情况
方法3适合一次性输入多个参数的情况
方法4在知道最大数量限制时使用
方法5最通用,可以处理各种类型的数据
方法1:使用vector和while循环(推荐)
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers;
int num;
cout << "请输入数字(输入非数字结束):" << endl;
while (cin >> num) {
numbers.push_back(num);
}
// 清除错误状态,以便后续输入
cin.clear();
cin.ignore(10000, '\n');
cout << "您输入了 " << numbers.size() << " 个数字:" << endl;
for (int i = 0; i < numbers.size(); i++) {
cout << "第" << i+1 << "个: " << numbers[i] << endl;
}
return 0;
}
方法2:使用字符串和特定结束符
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> inputs;
string input;
cout << "请输入内容(输入'end'结束):" << endl;
while (true) {
cin >> input;
if (input == "end") {
break;
}
inputs.push_back(input);
}
cout << "您输入了 " << inputs.size() << " 个参数:" << endl;
for (int i = 0; i < inputs.size(); i++) {
cout << "参数" << i+1 << ": " << inputs[i] << endl;
}
return 0;
}
方法3:读取一行然后分割
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
string line;
vector<string> tokens;
cout << "请输入多个参数(用空格分隔):" << endl;
// 读取整行
getline(cin, line);
// 使用stringstream分割
stringstream ss(line);
string token;
while (ss >> token) {
tokens.push_back(token);
}
cout << "您输入了 " << tokens.size() << " 个参数:" << endl;
for (int i = 0; i < tokens.size(); i++) {
cout << "参数" << i+1 << ": " << tokens[i] << endl;
}
return 0;
}
方法4:使用数组和计数器
#include <iostream>
using namespace std;
int main() {
const int MAX_SIZE = 100; // 设置最大数量
int arr[MAX_SIZE];
int count = 0;
int num;
cout << "请输入数字(最多" << MAX_SIZE << "个,输入-1结束):" << endl;
while (count < MAX_SIZE) {
cin >> num;
if (num == -1) {
break;
}
arr[count] = num;
count++;
}
cout << "您输入了 " << count << " 个数字:" << endl;
for (int i = 0; i < count; i++) {
cout << "第" << i+1 << "个: " << arr[i] << endl;
}
return 0;
}
方法5:处理混合类型参数牛牛牛牛牛牛牛牛牛牛牛牛牛牛牛!!
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
vector<string> params;
string input;
cout << "请输入任意数量的参数(输入'quit'退出):" << endl;
while (true) {
cout << "参数 " << params.size() + 1 << ": ";
cin >> input;
if (input == "quit") {
break;
}
params.push_back(input);
}
cout << "\n总共输入了 " << params.size() << " 个参数:" << endl;
for (int i = 0; i < params.size(); i++) {
cout << i+1 << ". " << params[i] << endl;
}
return 0;
}