题目:
文件hex.txt中有许多16进制正整数,范围在[0,7FFFFFFF]之间。
格式:每行一个16进制数,行末都有一个换行符号。
编写一个将16进制数转换成10进制数的函数,找出文件中的完全平方数,并以十六进制,十进制两种形式显示在屏幕上。
最后输出文件中总共有多少个数,找到多少个完全平方数。
1 #include <iostream> 2 #include <iomanip> 3 #include <fstream> 4 #include <cmath> 5 #include <cstdlib> 6 using namespace std; 7 8 // 将一个十六进制数转换成十进制数的函数 9 // 参数hex是存放16进制数据的字符数组,返回十进制整型数 10 int HexDec( char * hex ) 11 { int n, i; 12 n=0; i=0; 13 while( hex[i]!=‘\0‘ ) 14 { if( hex[i]>=‘0‘ && hex[i]<=‘9‘ ) 15 n=n*16 + hex[i]-‘0‘; 16 else if( hex[i]>=‘A‘ && hex[i]<=‘F‘ ) 17 n=n*16 + hex[i]-‘A‘+10; 18 else if( hex[i]>=‘a‘ && hex[i]<=‘f‘ ) 19 n=n*16 + hex[i]-‘a‘+10; 20 i++; 21 } 22 return n; 23 } 24 25 int main( void ) /* name: scanner.cpp */ 26 { char s[20]; 27 int num, count, k, total; 28 ifstream fin("hex.txt", ios::in); 29 if( !fin ) 30 { cerr<<"Error: Cannot open the file ‘hex.txt‘ to read.\n"; 31 exit(1); 32 } 33 count=0; //用于统计完全平方数的个数 34 total=0; //用于统计文件中总共有多少个数 35 fin.getline( s, 20 ); 36 while( !fin.eof( ) ) 37 { total++; 38 num = HexDec( s ); 39 k = (int)sqrt((double)num); 40 if( k*k==num ) 41 { count++; 42 cout<<setw(4)<<count<<": "<<setw(8)<<s<<‘\t‘ 43 <<num<<‘=‘<<k<<‘*‘<<k<<endl; 44 } 45 46 fin.getline( s, 20 ); 47 } 48 fin.close( ); 49 cout<<"\n文件中总共有"<<total<<"个十六进制整数,其中有" 50 <<count<<"个是完全平方数。\n"; 51 return 0; 52 }
数据文件下载:hex.rar
原文:http://www.cnblogs.com/jiutoushi/p/5012208.html