这是陈越数据结构的4-2,用c++改了一下,主体还是原来的程序,有一些细节改成了C++
#include<iostream>
#include<string>
#include<cstring>
#include <cstdio> //gets()需要这两个头文件
#include <cstdlib>
#include <iomanip> //设置精度需要这个头文件
const int Maxsize = 30;
using namespace std;
typedef struct TNode * BinTree;
struct TNode {
char treename[Maxsize + 1];
int count;
BinTree left;
BinTree right;
};
BinTree Insert(BinTree BT, char * name)
{
if (!BT)
{
BT = new struct TNode;
strcpy(BT->treename, name);
BT->count = 1;
BT->left = BT->right = NULL;
}
else
{
int cmp = strcmp(BT->treename, name);
if (cmp < 0)BT->right = Insert(BT->right, name);
else if (cmp > 0)BT->left = Insert(BT->left, name);
else
BT->count++;
}
return BT;
}
void Output(BinTree BT, int N)
{
if (!BT)return;
else
{
Output(BT->left, N);
cout << BT->treename << " " << setiosflags(ios::fixed) << setprecision(4) << (double)BT->count / (double)N * 100.0 << "%" << endl;
Output(BT->right, N);
}
}
int main()
{
BinTree BT = NULL;
int N;
cin >> N;
cin.get();
for (int i = 0; i<N; i++)
{
char name[Maxsize + 1];
gets(name);
BT = Insert(BT, name);
}
Output(BT, N);
cin.get();
return 0;
}
关于设置输出精度
cout << setiosflags(ios::fixed) <<setprecision(6) << endl; 为输出六位小数(小数点后保留6位)
cout << setprecision(3) << endl;为输出3位有效数字