如何在不使用字符串或数组的情况下从base n转换为base 10? [英] How do I convert from base n to base 10 without using strings or arrays?

查看:101
本文介绍了如何在不使用字符串或数组的情况下从base n转换为base 10?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用字符串或数组的情况下从base n转换为base 10(其中n是2到9之间的输入)?转换的数字是一个长整数类型。



我试过的代码返回输入到函数中的相同数字(num)。



我尝试过:



int calcBase10(long long num,int base) )

{

int base10;

int商;

int余数;



if(base == 10)

{

base10 = num;

return(base10);

}



商= num / base;

余数= num%base;

if(商= = 0)

{

base10 =余数;

}

else

{

base10 =(base * calcBase10(商,基数)+余数);

}

return( base10);

}

How do I convert from base n to base 10 without using strings or arrays(where n is an input between 2 and 9)? The number being converted is a long long integer type.

The code that I have tried returns the same number (num) that was input into the function.

What I have tried:

int calcBase10(long long num, int base)
{
int base10;
int quotient;
int remainder;

if(base == 10)
{
base10 = num;
return(base10);
}

quotient = num / base;
remainder = num % base;
if(quotient == 0)
{
base10 = remainder;
}
else
{
base10 = (base * calcBase10(quotient, base) + remainder);
}
return(base10);
}

推荐答案

你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到有一点它会停止你所期望的。

在Visual Studio 2010中掌握调试 - 初学者指南 [ ^ ]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html [ ^ ]
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]


当然是相同的数字输出作为输入!

任何整数(例如, long long )都是纯数字,即内部以二进制(基数2)表示。

它不是基数10,基数3等数字,直到它转换为/从某些其他表示形式(打印或输入)。

您可以编写一个函数,它接受 long long value 和一个int base 并返回一个字符串表示 作为基础 base 号码。

同样你可以编写一个相反的函数,取一个字符串和一个 base ,并返回已解析字符串的值,表示基本 base 号。
Of course it is the same number output as input!
Any integer (e.g., long long) is a pure number, that is internally represented in binary (base 2).
It isn't a base 10, base 3, etc. number until it is converted to/from some other representation (printed or input).
You can write a function that takes a long long value and an int base and returns a string representing that value as a base base number.
Likewise you can write a function that does the opposite, take a string and a base and returns the value having parsed the string as representing a base base number.


这篇关于如何在不使用字符串或数组的情况下从base n转换为base 10?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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