简体   繁体   English

将数字转换为具有多个参数的字符串

[英]Converting a number to string with multiple arguments

I want to convert a number x of a base n to a string and store it in str .我想将基数n的数字x转换为字符串并将其存储在str 中 str has the max size of max . str的最大大小为max In this program I don't want to use any library functions.在这个程序中,我不想使用任何库函数。 If I reach the maximum size of the array, the function should return false and the array contents should be undefined.如果我达到数组的最大大小,函数应该返回 false 并且数组内容应该是未定义的。

The prototype of the function looks like this:该函数的原型如下所示:

bool num2str(int x, char *str, unsigned n, unsigned max);

How would I go about making this work?我将如何进行这项工作? I'm having trouble understanding the algorithm behind it.我无法理解其背后的算法。

I also need to check the value of n , but I already did that:我还需要检查n的值,但我已经这样做了:

bool num2str(int x, char *str, unsigned n, unsigned max)
{
    assert(n >= 2 && n <= 36);
    return true;
}

But that's all I could do.但这就是我能做的。 Please help.请帮忙。

Let's take a number in base 10: 123456. Now let's repeatedly apply a modulus and an integer division using the number and base 10:让我们取一个以 10 为底的数字:123456。现在让我们使用数字和以 10 为底的重复应用模数和整数除法:

123456 mod 10 = 6
123456 div 10 = 12345

12345 mod 10 = 5
12345 div 10 = 1234

As you can see, modulus by base extracts the last digit, while integer division by base shifts the number on digit to the right.如您所见,按基数取模提取最后一位数字,而按基数进行整数除法将数字上的数字向右移动。 You can do the same for any base.你可以对任何基地做同样的事情。 Hope this hint is enough.希望这个提示足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM