javascript - 尝试运行 Javascript,使用函数将小数转换为其他基数

标签 javascript arrays function

函数 getNumber():

提示用户直到输入无符号整数。将无符号整数返回给调用代码。

函数 getBase():

提示用户直到输入有效的碱基。唯一有效的是“b”或“B”或“o”或“O”或“h”或“H”。返回调用代码的基数。

函数baseConversion(数字, 新基地):

返回转换为 newBase 的以 10 为基数的数字的字符串版本。例如,如果 number 为 255,newBase 为 16,则它将返回“FF”,因为 255 在基数 16 中是 FF。

function getNumber(callback) {
    var num = prompt("Enter an unsigned base 10 number");
    if (num >= 0) {
        callback();
        return num;
    }
}

function getBase() {
    var base = prompt("Enter b for binary, o for octal, or h for hexadecimal");
    return base;
}

function baseConversion(num, base) {
    var num = getNumber(function() {
        var base = getBase();
    });
    // problem here is that after calling the above two methods the program stops
    //does not return to the calling function to continue excuting

    if (base == "b" || base == "B") {
        var bin = [];

        while (num > 0) {
            bin.unshift(num % 2);
            num >>= 1; // basically /= 2 without remainder if any
        }
        alert("That decimal in binary is " + bin.join(''));
        return bin;
    }


    if (base == "o" || base == "O") {
        var oct = [];
        while (num > 0) {
            oct.unshift(num % 8);
            num = ~~ (num / 8);
        }
        alert("That decimal in octal is " + oct.join(''));
        return oct;
    }


    if (base == "h" || base == "H") {
        var hex = [];
        while (num > 0) {
            x = (num % 16);
            if (x > 9) {
                if (x == 10) {
                    hex.unshift("A")
                }
                if (x == 11) {
                    hex.unshift("B")
                }
                if (x == 12) {
                    hex.unshift("C")
                }
                if (x == 13) {
                    hex.unshift("D")
                }
                if (x == 14) {
                    hex.unshift("E")
                }
                if (x == 15) {
                    hex.unshift("F")
                }
            }
            if (x <= 9) {
                hex.unshift(x)
            }
            num = Math.floor((num / 16));
        }
        alert("That decimal in hexadecimal is " + hex.join(''));
        return hex;
    }
}

当我尝试运行代码时,代码停止工作。任何帮助将不胜感激

最佳答案

此回调系统的脚本过于复杂,但主要错误是您访问了不存在的变量base:

function baseConversion(num,base){
    var num = getNumber(function() {
        var base = getBase(); // this variable only exists within this function
    });
    // ... not here, where *base* is the argument passed to the function.

修复:

function baseConversion(num,base){
    // now the parameter *base* is updated:
    var num = getNumber(function() {
        base = getBase();
    });
    // ... and still has that same value here.

改进建议:

由于函数 baseConversion 已经接受 numbase 值作为参数,因此在该函数内请求输入的位置是错误的。相反,您应该在调用函数之前获取输入。

以线性方式请求输入,而不是回调方法,甚至更好:创建一个输入表单,用户可以在其中选择填写顺序以及何时启动该功能:

<input type="text" id="num"><br>
<input type="text" id="base"><br>
<button id="convert">Convert!</button>

这比使用 prompt 好得多,但是好吧,如果这是您对 prompt 的分配,我想您最好听听:)。

解决方案(剧透警告)

假设您不允许在代码中使用 toString(base),这将使其变得非常简单,以下是满足要求的内容:

function getNumber () {
    var num, input;
    do {
        input = prompt("Enter an unsigned base 10 number");
        num = parseInt(input);
    } while (isNaN(num) || num < 0 || num+''!==input);
    return num;
}

function getBase () {
    var base;
    do {
        base = prompt("Enter b for binary, o for octal, or h for hexadecimal");
    } while ('bBoOhH'.indexOf(base) === -1);
    return base;
}

function baseConversion(num, base){
    var baseNum = base === 'b' ? 2 :
                  base === 'o' ? 8 : 16;
    var res = [], digit;
    do {
        digit = num % baseNum;
        res.unshift('0123456789ABCDEFGH'.charAt(digit));
        num = (num - digit) / baseNum;
    } while (num > 0);
    return res.join('');
}

var num = getNumber();
var base = getBase();
var result = baseConversion(num, base);
alert('result is ' + result);

关于javascript - 尝试运行 Javascript,使用函数将小数转换为其他基数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36668164/

相关文章:

c - 是否可以强制函数参数在 C 中保持不变?

Javascript cookie 路径在 iOS 上无法正常工作。似乎是每页设置

php - Symfony 不能决定哪个类需要

javascript - 使用 TypeScript 函数返回 JSON 对象

arrays - Bash Looping 2 Arrays with whitespaces in variables

javascript - 检查 arraylist 属性是否对所有对象都为 true

java - 方法前面的泛型是什么意思?

javascript - 帮助用正则表达式替换文本

javascript - 如何使 visual studio javascript 格式化工作?

javascript - 访问 Angular 生成的内容时,evaluateJavaScript() 无法获取稳定的内容?