获得数字的十进制部分
Get decimal part of a number
试图将一个数字的整数和十进制部分分为两个变量。我尝试的是:
#include <iostream>
int main(){
float n,m; int k; std::cin >> n;
k = n;
m = n - k;
试图将浮点数转换为INT,并由编译器的警告收到警告,即该数字可能是不正确的,测试的,确实是不正确的,无法获得预期的结果。对此进行了搜索,除了使用floor()
。
我的实际代码:
int main() {
float n; cin >> n;
int nfloor = n;
cout << nfloor << "n";
float nfloat = n - nfloor; int nfloatfloor;
cout << nfloat << "n";
do {
nfloat *= 10;
nfloatfloor = nfloat;
cout << nfloat << "n" << nfloatfloor << "n";
} while (nfloat > nfloatfloor);
}
结果:
Input: 12.34
Output :
12
0.34
3.4
3
34
34
340
340
3400
3400
34000
34000
340000
340000
3.4e+06
3400001
3.4e+07
34000016
减去两个浮点数返回一个不正确的值,对此进行了搜索,但答案处于我无法理解的高级别。
我的实际代码:
int main() {
float n; cin >> n;
float nfloor = floor(n);
cout << nfloor << "n";
float nfloat = n - nfloor; float nfloatfloor;
cout << nfloat << "n";
do {
nfloat *= 10;
nfloatfloor = floor(nfloat);
cout << nfloat << "n" << nfloatfloor << "n";
} while (nfloat > nfloatfloor);
}
结果:
Input: 12.34
Output:
12
0.34
3.4
3
34
34 //Run should stop here because of the while loop bit it doesn't, funny thing is it gives me different results sometimes, last time it gave me 35 and 34
340
340
3400
3400
34000
34000
340000
340000
3.4e+06
3.4e+06
3.4e+07
3.4e+07
@slava查看该句子上方的输出,编译器打印了34和34,重复的答案表明,couts是34.0000000000000004或类似的东西,正如我在上面评论的那样,代码应该停止,我是我的。'我真的试图做的是比较一个浮点数和int编号,如果(float> int)代码应该继续并且应该停止,那么是否有任何解决方案?@hnefatl我尝试了您的答案,编译器只是悬挂:
int main() {
float n2, whole, fractional, fractional2, whole2; cin >> n2;
int denominator = 1;
fractional = modf(n2, &whole);
do {
fractional *= 10;
fractional2 = modf(fractional, &whole2);
denominator *= 10;
} while (fractional > fractional2);
if (denominator > 1)
denominator /= 10;
cout << denominator;
}
为什么不使用为此目的而设计的std::modf
:
float n = 12.34;
float whole, fractional;
fractional = std::modf(n, &whole);
该值的非分数部分在whole
中,而分数部分则为fractional
。
如果您想获得整个部分的整数值(牢记,您可能会以这种方式丢失数据,因为float
的范围可能大于int
的范围),您可以做:
int integralWhole = static_cast<int>(whole);
这应该可以解决问题。
int main(){
float n; std::cin >> n;
float whole = floor(n);
float decimal = n - whole;
std::cout << whole << "n";
std::cout << decimal << "n";
std::cin.get();
return 0;
}
相关文章:
- 计算十进制 c++ 之后的数字
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 如何计算整数的十进制数字?
- 使用正则表达式C++计算数字中的十进制空格
- Unicode Chars显示为十进制数字而不是符号,我该如何修复
- 根据参数设置十进制数字
- 将二进制号转换为十进制数字的代码
- 使用动态比特斯转换十进制数字
- 获得数字的十进制部分
- 此代码中 * 1233 >> 12 计算十进制数字背后的数学原理是什么
- 仅使用char将八分音号码转换为十进制数字
- 如何使用C 将二进制数字的字符串转换为其签名的十进制表示
- 努力理解一个以十六进制、十进制、bin 和 dec 计算数字总和的程序
- C 如何将双重转换为字符串,因此它仅在十进制后显示2位数字
- 将十进制数字截断为最接近的4个小数和断言
- 打印长双变量的所有十进制数字
- 十进制数字的区域设置感知编辑控件子类化(格式[sign][xxx..][decimal separator][yy.])
- 反向数字十进制
- 将双精度转换为精度超过 5 位十进制数字的字符串
- 如何通过 calcBackProject 获得包含超过 255 或十进制的数字的反向投影矩阵