Noob关于花车的问题 [英] Noob question about floats

查看:63
本文介绍了Noob关于花车的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>


using namespace std;
void toBase (float n, float base)
{
string x = "0123456789ABCDEF";
if (n > 0)
{
toBase(n / base, base);
cout << x[n % base];
}
}


main() {
int a;
float num;
cout << "";
cin >> num;
cout << "";
cin >> a;
toBase(num, a);

}





我遇到这行代码时出现问题 - cout<< x [n%base]; - 我收到一条错误消息,因为我不能使用%浮动,而且由于x而无法实现fmod。那段代码应该如何看起来我的程序可以正确地打印十个小数?使用float时我需要一个合适的替代%。我应该使用什么函数?



I''m having trouble with this line of code - cout << x[n % base]; - i get an error message because i can''t use % with float, and i''m having trouble implementing fmod due to x. How should that line of code look so my program can print out ten decimals correctly? I need a suitable substitute for % while using float. What function should i use?

推荐答案

你不能将%与浮点数一起使用,因为当你不是在谈论整数值时,模数是没有意义的绝对绝不是。相反,尝试将 n 转换为整数(并与 x 的大小进行比较以限制值的范围)。
You can''t use % with floats because modulus makes no sense when you aren''t talking about integer values, which floats most definitely never are. Instead, try casting n as an integer (and do a comparison with the size of x to limit the range of values).


算法被破坏:

您永远不会在整数和小数部分之间输出分隔符。

这个算法可以用于正整数。

关于索引到字符串x ,要么<在<$ c之前code> n 到 int (或 long ) $ c>%或使用 fmod 并投射结果。
The algorithm is broken:
You never output the delimiter between the whole number and fractional parts.
This algorithm could work for positive integers.
Regarding indexing into the string x, either cast n to int (or long) before the % or use fmod and cast the result.


这篇关于Noob关于花车的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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