博客
关于我
判断两个实数是否相等
阅读量:311 次
发布时间:2019-03-01

本文共 2074 字,大约阅读时间需要 6 分钟。

C程序示例:判断两个字符串表示的数字是否相等

#include 
#include
#define MAX 1000005
char a[MAX], b[MAX];
int main() {
while (~scanf("%s%s", a, b)) {
int len_a = strlen(a);
int len_b = strlen(b);
bool has_decimal_a = false;
bool has_decimal_b = false;
// 检查字符串中是否包含小数点
for (int i = 0; i < len_a; i++) {
if (a[i] == '.') {
has_decimal_a = true;
break;
}
}
for (int i = 0; i < len_b; i++) {
if (b[i] == '.') {
has_decimal_b = true;
break;
}
}
// 如果字符串中没有小数点,添加小数点
if (!has_decimal_a) {
a[len_a] = '.';
}
if (!has_decimal_b) {
b[len_b] = '.';
}
// 比较字符串的长度,补零到较短的字符串
if (strlen(a) < strlen(b)) {
// 如果a没有小数点,补零从小数点后第一位开始
if (!has_decimal_a) {
for (int i = len_a + 1; i < strlen(b); i++) {
a[i] = '0';
}
} else {
// 如果a有小数点,补零从小数点后第一位开始
for (int i = len_a; i < strlen(b); i++) {
a[i] = '0';
}
}
} else if (strlen(a) > strlen(b)) {
// 如果b没有小数点,补零从小数点后第一位开始
if (!has_decimal_b) {
for (int i = len_b + 1; i < strlen(a); i++) {
b[i] = '0';
}
} else {
// 如果b有小数点,补零从小数点后第一位开始
for (int i = len_b; i < strlen(a); i++) {
b[i] = '0';
}
}
}
// 比较两个字符串是否相等
if (strcmp(a, b) == 0) {
printf("YES\n");
} else {
printf("NO\n");
}
}
return 0;
}

说明:这段代码实现了一个简单的字符串比较功能,主要用于判断两个字符串表示的数字是否相等。程序首先读取两个字符串,并检查它们是否包含小数点。如果字符串中没有小数点,程序会在末尾添加小数点。然后,程序会根据字符串的长度补零到较短的字符串,使其与较长的字符串长度相同。最后,程序比较两个字符串是否相等,并输出结果。

这个程序适用于处理类似的问题,比如比较两个数是否相等,无论它们是整数还是带有小数点的浮点数。程序通过检查小数点的存在情况和字符串的长度,确保数字的准确性和比较的有效性。

转载地址:http://ysto.baihongyu.com/

你可能感兴趣的文章
npm切换源淘宝源的两种方法
查看>>
npm前端包管理工具简介---npm工作笔记001
查看>>
npm包管理深度探索:从基础到进阶全面教程!
查看>>
npm升级以及使用淘宝npm镜像
查看>>
npm发布包--所遇到的问题
查看>>
npm发布自己的组件UI包(详细步骤,图文并茂)
查看>>
npm和package.json那些不为常人所知的小秘密
查看>>
npm和yarn清理缓存命令
查看>>
npm和yarn的使用对比
查看>>
npm如何清空缓存并重新打包?
查看>>
npm学习(十一)之package-lock.json
查看>>
npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
查看>>
npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
查看>>
npm安装教程
查看>>
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>