gpt4 book ai didi

c++ - 如何将 double 或 float(所有数字)转换为 int?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:39:17 24 4
gpt4 key购买 nike

如何将 double 或 float(所有数字)转换为 int?

例如,如果我有一个 double 0.9332,函数将返回 9332,1.32001 将返回 132001

最佳答案

this will work ! question is similar to this one :
https://stackoverflow.com/questions/5314954/how-to-get-the-length-of-a-numbers-fraction-part

#include <iostream>
#include <math.h>
using namespace std;
int getFractionDigitsCount(float );
int main()
{
float a=1.9332;
int p = getFractionDigitsCount(a);
cout<<"answer is : "<< a * pow(10,p);

return 0;
}
int getFractionDigitsCount(float d) {
if (d >= 1) { //we only need the fraction digits
d = d - (long) d;
}
if (d == 0) { //nothing to count
return 0;
}
d *= 10; //shifts 1 digit to left
int count = 1;
while (d - (long) d != 0) { //keeps shifting until there are no more fractions
d *= 10;
count++;
}
return count;
}

关于c++ - 如何将 double 或 float(所有数字)转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55016254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com