#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "1234.56789";
    int len = strlen(str);
    int dot_pos = -1;
    for (int i = 0; i < len; i++) {
        if (str[i] == '.') {
            dot_pos = i;
            break;
        }
    }
    if (dot_pos == -1) {
        printf("Error: no decimal point\n");
        return 0;
    }
    if (len - dot_pos - 1 < 2) {
        printf("Error: less than 2 decimal places\n");
        return 0;
    }
    str[dot_pos+3] = '\0';
    printf("Result: %s\n", str);
    return 0;
}

输出结果为:Result: 1234.5

123456789 是一个字符串需要保留两位小数并且最后还放在字符数组里面提示可以用先找到小数点的方式实现用c语言实现

原文地址: https://www.cveoy.top/t/topic/fn5j 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录