1684838553 / arithmeticQuestions

程序员的算法趣题
2 stars 0 forks source link

N进制小数 #4

Open 1684838553 opened 2 years ago

1684838553 commented 2 years ago

题目描述

编写程序实现将任意10进制正小数m转换成n进制的正小数,小数点后保留10位小数。

解答要求

时间限制:1000ms, 内存限制:100MB

输入

输入包含两个数m,n,用空格隔开。输入包含多组测试,当m,n都为0时输入结束。

Limits:

0.0000009<m<1
1<n<10

输出

输出10进制正小数m的n进制小数。结果保留10位小数。

样例

0.795 3
0 0

输出样例 1

0.2101101122
1684838553 commented 2 years ago

方法一

// please define the JavaScript input here(you can also rewrite the input). 
// following is the default: 
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let input = '';
process.stdin.on('data', (data) => {
  input += data;
});

process.stdin.on('end', () => {
  let inputArray = input.split('\n');
    inputArray.pop()
   inputArray.forEach(item=>{
       let [m,n] = item.split(' ').map(item=>+item)
       if(m && n){
          const [a,b] = m.toString(n).split('.')
           console.log(a + '.' +b.slice(0,10)) 
       }

   })
  // please finish the function body here.       
  // please define the JavaScript output here. For example: console.log(result);
  process.exit();
});
1684838553 commented 2 years ago

方法二

// please define the JavaScript input here(you can also rewrite the input). 
// following is the default: 
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let input = '';
process.stdin.on('data', (data) => {
    input += data;
});
process.stdin.on('end', () => {
    let inputArray = input.split('\n');
    // please finish the function body here.       
    // please define the JavaScript output here. For example: console.log(result);
    inputArray.forEach(el => {
        let n = el.split(" ")[0]
        let radix = el.split(" ")[1]
        if (n != 0 && radix != 0) {
            let str =transDecimals(n, radix, 10)
            console.log(str)
        }
    })
    process.exit();

    function transDecimals (n, radix, precision) {
        let ret = ""
        while (ret.length < precision) {
            n *= radix
            //  |0 得整数部分
            ret += n | 0
            //  %1 得小数部分
            n = n % 1
        }
        return "0." + ret
    }
});