找出文件中的完全平方数
2015-12-02 10:30
726 查看
题目:
文件hex.txt中有许多16进制正整数,范围在[0,7FFFFFFF]之间。
格式:每行一个16进制数,行末都有一个换行符号。
编写一个将16进制数转换成10进制数的函数,找出文件中的完全平方数,并以十六进制,十进制两种形式显示在屏幕上。
最后输出文件中总共有多少个数,找到多少个完全平方数。
View Code
数据文件下载:hex.rar
文件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
相关文章推荐
- compass模块----Helpers
- OpenCv ROI操作
- HTTP请求中浏览器的缓存机制
- LeetCode-- Palindrome Number
- SQL----函数
- watchOS 2 教程(四): Watch Connectivity
- c/c++ 数字转字符串, 字符串转数字
- SpringMVC整合Tiles框架
- android EditText禁止复制粘贴完整代码
- D. Mike and Feet---cf548D(最值)
- jquery图片预览
- 旧文重整之-> HASH集
- 局部保留投影(LPP)推导
- mysql 安装脚本
- LeetCode-- Move Zeroes
- OpenCV图像金字塔:高斯金字塔、拉普拉斯金字塔与图片尺寸缩放
- HTML标签自定义属性
- 安卓5.0后httpclient
- Apache配置缺失msvcr100.dll msvcr110.dll
- JS弹出框,弹出层