使用基数 10 转换数字的程序中的控制流

Control flow in a program that transforms a number using base 10

这是一个进行数字转换的程序,我试图理解这段代码的控制流程。

不太清楚while循环的第一遍中cn的值是什么,意思是如果我们在程序的开头声明cn = n,cn的第一个值是否就是n的第一个值或者它将是在第一个 while 循环中计算的 n 的值,即 n/=10.

一些提示会有所帮助...谢谢!

int n, cn, x=0,p=1;  

cin>>n;  

cn=n;  

while(n)  {   
    if (n%10>x) {x=n%10;}   
    n/=10;
} 

x++;  

while(cn)   {    
    n= n + cn%10 *p;   
    p*=x;    
    cn/=10;
}  

cout<<n; 

cn = n”的赋值语句为

暂时将n的值赋给cn,

在 n 将在 while 循环内被修改之前。

这是添加了打印语句的程序,用于说明值是如何变化的:

#include <iostream>
using namespace std;

int main() {
    int n, cn, x = 0, p = 1;
    cout << "Enter the value of n: ";
    cin >> n;  

    cout << " n = " << n << " , cn = " << cn << "\n";
    cout << "Temporarily assigning the value of n to cn \n";

    cn = n;  
    cout << " n = " << n << " , cn = " << cn << "\n";

    while(n)  {   
        if ( n%10 > x ) {
            x = n%10;
        }
        n /= 10;
    }

    x++;

    cout << "Intermediate value of n = " << n << "\n";
    while( cn ) {
        n = n+cn%10*p;   
        p *= x;
        cn /= 10;
    }
    cout<<"Final value of n = " << n << "\n";
    return 1;
}

输出:

Enter the value of n: 12345
 n = 12345 , cn = 0
Temporarily assigning the value of n to cn 
 n = 12345 , cn = 12345
Intermediate value of n = 0
Final value of n = 1865

另一个问题是,

如果在程序的第一条语句中使用cn=n会怎样?

即,

int n, cn=n, x = 0, p = 1;

答案:这将为cn分配一个随机值。

下面是 int n, cn=n 语句的演示:

#include <iostream>
using namespace std;

int main() {
    int n, cn=n, x = 0, p = 1;
    cout << "Enter the value of n: ";
    cin >> n;  

    cout << " n = " << n << " , cn = " << cn << "\n";

    while(n)  {   
        if ( n%10 > x ) {
            x = n%10;
        }
        n /= 10;
    }

    x++;

    cout << "Intermediate value of n = " << n << "\n";
    while( cn ) {
        n = n+cn%10*p;   
        p *= x;
        cn /= 10;
    }
    cout<<"Final value of n = " << n << "\n";
    return 1;
}

int n 的输出,cn=n :

Enter the value of n: 12345
 n = 12345 , cn = 4196992
Intermediate value of n = 0
Final value of n = 207740