gpt4 book ai didi

c - 除算法 C 得到 float

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:48:44 26 4
gpt4 key购买 nike

您好,我得到了这个除法算法来显示整数和浮点值。我怎样才能得到 MAX_REM?它应该是我们的字符将要存储的缓冲区的大小,所以大小必须是数字的#,但我不知道如何得到它。谢谢!

void divisionAlg(unsigned int value)
{

int MAX_BASE=10;
const char *charTable = {"0123456789ABCDEF"}; // lookup table for converting remainders
char rembuf[MAX_REM + 1]; // holds remainder(s) and provision null at the end
int index; //
int i; // loop variable

unsigned int rem; // remainder
unsigned int base; // we'll be using base 10
ssize_t numWritten; // holds number of bytes written from write() system call

base = 10;

// validate base
if (base < 2 || base > MAX_BASE)
err_sys("oops, the base is wrong");

// For some reason, every time this method is called after the initial call, rembuf
// is magically filled with a bunch of garbage; this just sets everything to null.
// NOTE: memset() wasn't working either, so I have to use a stupid for-loop
for (i=0; i<MAX_REM; i++)
rembuf[i] = '\0';

rembuf[MAX_REM] = 0; // set last element to zero
index = MAX_REM; // start at the end of rembuf when adding in the remainders

do
{
// calculate remainder and divide valueBuff by the base
rem = value % base;
value /= base;

// convert remainder into ASCII value via lookup table and store in buffer
index--;
rembuf[index] = charTable[rem];

} while (value != 0);

// display value
if ((numWritten = write(STDOUT_FILENO, rembuf, MAX_REM + 1)) == -1)
err_sys("something went wrong with the write");

} // end of divisionAlg()

最佳答案

计算一个数字有多少位的计算方法是:

digits = floor(log(number)/log(base))+1;

但是,在这种情况下,我可能只是假设最坏的情况,因为它不超过 32,并且计算它会很“昂贵”。所以只需 #define MAX_REM 32,然后跟踪您实际放入 rembuf 的位数(您已经为此设置了 index,所以这真的没有额外费用)。您显然还需要计算要写出的字节数,但不需要任何特殊的数学运算。

关于c - 除算法 C 得到 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14610165/

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