C语言实现数字四舍五入:安全读取输入并处理小数点
以下是已经更新的代码的中文版本:
#include <stdio.h>
#include <string.h>
int main() {
char s[1001];
// 读取输入的数字
fgets(s, sizeof(s), stdin);
s[strcspn(s, '\n')] = '\0'; // 去除末尾的换行符
// 查找小数点并进行四舍五入
char* dot = strchr(s, '.');
if (dot != NULL) {
int dotIndex = dot - s;
if (s[dotIndex-1] != '9') {
if (s[dotIndex+1] < '5') {
for (int i = 0; i < dotIndex; i++) {
printf('%c', s[i]);
}
} else {
for (int i = 0; i < dotIndex-1; i++) {
printf('%c', s[i]);
}
printf('%c', s[dotIndex-1] + 1);
}
} else {
printf("GOTO Vasilisa.");
}
}
return 0;
}
在更新的代码中,我们使用fgets安全地读取输入。使用strchr查找小数点字符,并根据算法执行四舍五入逻辑。根据条件打印四舍五入后的数字或者消息 'GOTO Vasilisa.'。
请注意,代码假设输入的数字符合给定的格式和限制。根据实际需求,你可以进一步修改代码以处理错误情况和边界情况。
原文地址: https://www.cveoy.top/t/topic/Sp4 著作权归作者所有。请勿转载和采集!