如何理解这些函数背后的逻辑?

huangapple go评论62阅读模式
英文:

How to understand logic behind these functions?

问题

#include <iostream>
#include <cstring>

using namespace std;

long digitToLong(char c) { // 函数返回类型 long(c - '0'),以字符 c 作为参数。
    return c - '0';  // c 等于(text[i]),0 是 ASCII 码中的数字 0。
}

long toLong(string text) { /* 将代表数字的文本转换为数字。 */
    long result = 0;

    for (int i = 0; i < text.length(); i++) { /* 循环遍历文本中的每个字符。 */
        result *= 10;  // 将结果乘以 10。
        result += digitToLong(text[i]);  // 将字符转换为数字并加到结果中。
    }

    return result;
}

int main() {
    char number[] = "0123456789";

    cout << (toLong("0") == 0) << endl;
    cout << (toLong("1") == 1) << endl;
    cout << (toLong("2") == 2) << endl;
    cout << (toLong("5") == 5) << endl;
    cout << (toLong("12") == 12) << endl;
    cout << (toLong("123") == 123) << endl;
    cout << (toLong("12345") == 12345) << endl;
}

在上面的代码中,我的老师使用了字符串到长整型的转换方法,其中我们将每个字符与其 ASCII 值进行比较,然后获取该数字字符的值。我试图想象这个转换的过程,但卡在代码的两行上,因此我将我的问题提交给 StackOverflow 社区,希望能得到解答。这两行是 result *= 10;result += digitToLong(text[i]);,它们是否可以写成 result = result * 10 + (c - '0')?这样理解对吗?为什么我们需要将 result 乘以 10?我猜想这是因为在十进制中,乘以 10 会将所有数字向左移动,改变其值。在这段代码中如何应用这个概念?背后的“机制”是什么?

在这段代码中,c 被分配了什么?如何阅读它?c 是否等于 text[i]?那么 text[i] 下面是什么?是 for 循环的一个迭代吗?如何计算它?我真的尽量理解程序的逻辑(特别是函数的部分),但有些部分还是难以理解。

在提问之前,我已经尽力做了研究,真诚地希望我的问题能够得到解答。

英文:
#include &lt;iostream&gt;
#include &lt;cstring&gt;

using namespace std;

long digitToLong(char c) { // function returns the value type long (c - &#39;0&#39;) and takes the char c as an argument. 
    return c - &#39;0&#39;;  // c is equal to (text[i]) and 0 is the code ascii assigned as a nr 0.
}

long toLong(string text) {. /* takes a text that represents a number and then transfers              the text into a number.*/
    long result = 0;  

    for (int i = 0; i &lt; text.length(); i++) { /* for loop that iterates through every character included in a text length.*/
        result *= 10;  
        result += digitToLong(text[i]); 
    }

    return result;
}


int main() {
    char number[] = &quot;0123456789&quot;;

    cout &lt;&lt; (toLong(&quot;0&quot;) == 0) &lt;&lt; endl; 
    cout &lt;&lt; (toLong(&quot;1&quot;) == 1) &lt;&lt; endl;
    cout &lt;&lt; (toLong(&quot;2&quot;) == 2) &lt;&lt; endl;
    cout &lt;&lt; (toLong(&quot;5&quot;) == 5) &lt;&lt; endl;
    cout &lt;&lt; (toLong(&quot;12&quot;) == 12) &lt;&lt; endl;
    cout &lt;&lt; (toLong(&quot;123&quot;) == 123) &lt;&lt; endl;
    cout &lt;&lt; (toLong(&quot;12345&quot;) == 12345) &lt;&lt; endl;
}

In the code above my teacher used the method of string-to-long conversion where we compare each character to its ASCII values and then get the value of that numeric character. I'm trying to picture the process of this conversion and I'm stuck on two lines of the code above therefore I'm direct my question to the StackOverflow community, hoping this can be answered. The line result *= 10; and result += digitToLong(text[I]) could be also written as a  result = result * 10 + (c - &#39;0&#39;) Is that correct? Why do we need to multiply result by 10? I assume it's because in decimal, multiplying by 10 moves all digits to the left changing its values. How it applies in this code in reality? What is the "mechanic" behind it?

What exactly is assigned to c in this code? How to read it? Ic c equal to text[I]? What is under text[I] then? an iteration of the for loop? How to count it? I really try to understand the logic of the program (especially the functions) but some parts are unbearable yet.

I did my research before best as I could and I really hope my question could be answered.

答案1

得分: 3

Q1. 代码的目的和机制是什么?

long toLong(string text) {. /*接受一个代表数字的文本,然后将文本转换为数字。*/
    long result = 0;  

    for (int i = 0; i &lt; text.length(); i++) { /*循环遍历文本的每个字符。*/
        result *= 10;  
        result += digitToLong(text[i]); 
    }

    return result;
}

你说得对。这是因为你要逐个从左侧(最高位数字)获取数字,但需要将它们从右侧插入。

让我们来详细解释一下。

  • 第一次进入循环,
    • 当前,result = 0,所以乘以 10 不起作用。
    • 然后,text[i] 获取第一个位置(从左侧开始)的一个数字,因为当前 i = 0
  • 所有其他情况
    • 乘以 10 实际上将所有数字向左移动。新数字应插入的位置现在是一个 0。
    • 由于 digitToLong() 只获取一个数字,将该数字简单地添加到 result 中与将其粘贴到最右边位置相同。

Q2. 这里的 ctext[i] 是什么作用?
我假设你了解数组或向量。字符串的工作方式相同,只不过这次是一堆 char(字符)。当你使用 string[i] 时,它只是从左侧开始,从零开始获取第 i 个字符。

例如,你在字符串 string str = "abcdefg" 上调用 str[3],实际上是 d。然后,你将它传递给 digitToLong()

最后,你执行字符之间的减法。你如何做到的呢?

在 ACSII 代码表中(Google 搜索一下!),你可以看到当你有一个字符 0 时,它实际上在内部存储为数字 48。'1' 是 49,'2' 是 50,依此类推。利用这个特性,减去 '0' 实际上会得到正确的数字值(例如,'1' - '0' 实际上执行 49 - 48,得到 1),因此你会在函数中看到字符减法。

希望你现在能理解了。

英文:

Q1. Whats the purpose and mechanism of the code?

long toLong(string text) {. /* takes a text that represents a number and then transfers              the text into a number.*/
    long result = 0;  

    for (int i = 0; i &lt; text.length(); i++) { /* for loop that iterates through every character included in a text length.*/
        result *= 10;  
        result += digitToLong(text[i]); 
    }

    return result;
}

You are correct. This is performed because you get the digits one-by-one from the left (most-significant-digit) but you need to insert it from the right.

Lets try to break it down.

  • First time entering the loop,
    • Currently, result = 0, so the multiply by 10 does nothing.
    • Then, text[i] gets 1 digit, in character form, at the first position from left, since i = 0 currently.
  • All other enterings
    • Multiplying by 10 effictivly moves all the numbers to the left. The position where the new digit should be is now a 0.
    • Since digitTolong() get only 1 digit number, simply adding the number to result is same as pasting it onto the rightmost position.

Q2. What does c and text[i] do here?

I assume you know about an array, or a vector. The string acts the same, except this time, its a bunch of char (characters). When you use string[i], its simply gets you the i-th character from the left, starting from zero.

For example, you call str[3] on string str = &quot;abcdefg&quot;, its basically &#39;d&#39;. Then, you pass it in to digitToLong().

Lastly, you perform a subtraction between characters. How do you do it?

In the ACSII code table (google it!), you can see that when you have a charatcter 0, its actually stored internally as the number 48. &#39;1&#39; is 49, &#39;2&#39; is 50, and so on. <br> Using this property, minusing &#39;0&#39; actually gets us the correct value of the digit (for example, &#39;1&#39; - &#39;0&#39; actually does 49 - 48 which gets you 1.), thus you see the character subtraction in the function.

Hope you can understand now.

答案2

得分: 0

int charToDigit(char c)
{
    return c - '0';
}

在这个函数中,我们将字符的ASCII值转换为实际的数字
如果字符是'1',那么ASCII值是49,我们将49减去48'0'字符),得到1

long toLong(string strNumber)
{
    long result = 0;  
    
    for (int i = 0; i < strNumber.length(); i++)
    {
        result *= 10;
        result += charToDigit(strNumber[i]);
    }
    
    return result;
}

而在这个函数中,你从函数得到的字符串中逐个迭代数字,所以如果你得到了"123",你会依次迭代'1''2',最后'3'

在每次迭代中,你会将结果乘以10,将已经添加到结果中的数字左移一位,然后再将结果加上下一个数字,将下一个数字附加到结果上。
英文:
int charToDigit(char c)
{
    return c - &#39;0&#39;;
}

In this function, we convert the ASCII of the character to the real digit.
If the character is &#39;1&#39; so ASCII is 49, we subtract the 48 (&#39;0&#39; character) from the 49 to have 1.

long toLong(string strNumber)
{
    long result = 0;  

    for (int i=0; i&lt;strNumber.length(); i++)
    {
        result *= 10;
        result += charToDigit(strNumber[i]); 
    }

    return result;
}

And in this function, you iterate the string you got from the function from the first digit, so if you got &quot;123&quot; you iterate &#39;1&#39;, &#39;2&#39; and the last &#39;3&#39;.

In each iteration, you just *= 10 the result, to shift the numbers added to the result to the left, and again the += the result with the next digit to append the next digit to the result.

huangapple
  • 本文由 发表于 2023年6月22日 16:57:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76530169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定