错误印出双数 [英] printing the double number wrongly

查看:61
本文介绍了错误印出双数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写代码,如果我输入一个十进制数字(如612.216),则可以将其打印为612216(实际上将其转换为整数).但是,该程序将我的电话号码更改为2162160000000000000000001之类的东西,而我不知道要怎么做.

I want to write code that, if I input a decimal number like 612.216, I can print it as a 612216 (actually convert it to integer). However, the program changes my number to something like 2162160000000000000000001 and I don't what to do about it.

这是我的代码:

#include <stdio.h>
#include <math.h>
int main() {

long double x;
scanf_s("%Lf", &x);
while (floor(x)!=x)
    x = x * 10;

printf("%Lf", x);

return 0;}

推荐答案

这是怎么回事:

#include <stdio.h>
int main() {
    double number =  612.216; 
    char number_as_string[20];
    snprintf(number_as_string,"%lf", number);
    for(int i = 0; number_as_string[i] != '\0'; i++)
        if(number_as_string[i] != '.')
        printf("%c", number_as_string[i]);
    return 0; 
}

缺点是静态分配的数组.您可以使用snprintf将 double 转换为 chars数组.

The downside is the statically allocated array. You can use snprintf to convert the double into an array of chars.

这篇关于错误印出双数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆