您的位置:首页 > 其它

找出文件中的完全平方数

2015-12-02 10:30 726 查看
题目:

文件hex.txt中有许多16进制正整数,范围在[0,7FFFFFFF]之间。
格式:每行一个16进制数,行末都有一个换行符号。
编写一个将16进制数转换成10进制数的函数,找出文件中的完全平方数,并以十六进制,十进制两种形式显示在屏幕上。
最后输出文件中总共有多少个数,找到多少个完全平方数。

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;

//    将一个十六进制数转换成十进制数的函数
//  参数hex是存放16进制数据的字符数组,返回十进制整型数
int HexDec( char * hex )
{   int n, i;
n=0;    i=0;
while( hex[i]!='\0' )
{   if( hex[i]>='0' && hex[i]<='9' )
n=n*16 + hex[i]-'0';
else if( hex[i]>='A' && hex[i]<='F' )
n=n*16 + hex[i]-'A'+10;
else if( hex[i]>='a' && hex[i]<='f' )
n=n*16 + hex[i]-'a'+10;
i++;
}
return n;
}

int main( void )    /* name: scanner.cpp */
{    char s[20];
int num, count, k, total;
ifstream fin("hex.txt", ios::in);
if( !fin )
{    cerr<<"Error: Cannot open the file 'hex.txt' to read.\n";
exit(1);
}
count=0;    //用于统计完全平方数的个数
total=0;    //用于统计文件中总共有多少个数
fin.getline( s, 20 );
while( !fin.eof( ) )
{    total++;
num = HexDec( s );
k = (int)sqrt((double)num);
if( k*k==num )
{    count++;
cout<<setw(4)<<count<<": "<<setw(8)<<s<<'\t'
<<num<<'='<<k<<'*'<<k<<endl;
}

fin.getline( s, 20 );
}
fin.close( );
cout<<"\n文件中总共有"<<total<<"个十六进制整数,其中有"
<<count<<"个是完全平方数。\n";
return 0;
}


View Code

数据文件下载:hex.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: