题目
要求使用指针处理下面的问题,输入四个整数,按由小到大的顺序输出;然后将程序改为:输入四个字符串,按由小到大顺序输出。
整数大小比较
#include<iostream>
using namespace std;
void swap(int*, int*);
int main()
{
int a, b, c, d;
cout << "请输入四个整数:";
cin >> a >> b >> c >> d;
//这里我使用了感觉笨笨的方法进行比较,待日后学习更多
if (a > b) swap(&a, &b);
if (b > c) swap(&b, &c);
if (a > b) swap(&a, &b);
if (c > d) swap(&c, &d);
if (b > c) swap(&b, &c);
if (a > b) swap(&a, &b);
cout << "由小到大排序:";
cout << a << "/t"<< b <<"/t"<< c <<"/t"<< d << endl;
return 0;
}
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
打印结果
字符串大小比较
通过更改上面的代码。
#include<iostream>
using namespace std;
void swap(string*, string*);
int main()
{
/*要求使用指针处理下面的问题,输入四个整数,
按由小到大的顺序输出;然后将程序改为:输入四个字符串,
按由小到大顺序输出。*/
string a, b, c, d;
cout << "请输入四个字符串:";
cin >> a >> b >> c >> d;
if (a > b) swap(&a, &b);
if (b > c) swap(&b, &c);
if (a > b) swap(&a, &b);
if (c > d) swap(&c, &d);
if (b > c) swap(&b, &c);
if (a > b) swap(&a, &b);
cout << "由小到大排序:";
cout << a << " "<< b <<" "<< c <<" "<< d << endl;
return 0;
}
//变量交换
void swap(string* a, string* b)
{
string temp = *a;
*a = *b;
*b = temp;
}
打印结果
更改过程中,起初将int改为char,无法比较多个字母的字符串,故改为string类型
C++初学者还望大家指正。