最近正在准备软考,发现自己对10进制转二进制 计算记忆能力不怎么深了。当然,在本子上算出来,然后背一背也记得住的,但是那就有点乏味了。所以花半个小时,写了shell交互小程序.
1.程序会随机从0-15 产生一个十进制的说,在控制台提示输入十六进制的字符
2.键盘输入相应的字符。直接回车(Enter键)
3.程序会根据输入的结果判断你的输入是否正确
4.输入exit 敲回车或者(Ctrl+C)会退出程序.并统计你的训练结果
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const colors = {
reset: '\x1b[0m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
};
// 统计结果
let correctly =0;
let mistakes=0
let passRate='0%'
let start=new Date()
// 0-15 随机生成一个二进制
let randomNum = Math.floor(Math.random() * 15)
function rlClose(){
if(!mistakes==0&&!correctly==0){
passRate=(correctly/(mistakes+correctly)*100).toFixed()+ '%'
}
console.log(colors.yellow+'恭喜你!完成测试!测试结果如下:');
console.log(colors.green+'正确:'+correctly);
console.log(colors.green+'错误:'+mistakes);
console.log(colors.green+'通过率:'+passRate);
const timeDifference = new Date() - start;
let minutesDifference =0;
const isSecond=timeDifference<=1000 * 60
// 转换为分钟
if(isSecond){
minutesDifference = timeDifference / (1000);
}else{
minutesDifference = (timeDifference / (1000 * 60)).toFixed(3);
}
console.log(colors.green+'总用时:'+minutesDifference+(isSecond?'秒':'分钟'));
// 关闭readline接口
rl.close();
}
// 交互式输入
function interactiveShell(pass) {
if(pass){
randomNum = Math.floor(Math.random() * 15)
}
let msg=colors.blue+"请输入"+randomNum.toString(2)+"的16进制:"
rl.on('SIGINT', function() {
// 用户按下了 Ctrl + C 中断程序
rlClose()
});
rl.question(msg, (userInput) => {
if (userInput === 'exit') {
rlClose()
return;
}
if(userInput.toLocaleLowerCase()==randomNum.toString(15)){
console.log(colors.green+'真棒!你输入答案是正确的,答案是', userInput);
interactiveShell(true);
correctly++
}else{
console.log(colors.red+'很遗憾!这不是正确答案:你输入是:', userInput);
interactiveShell();
mistakes++
}
});
}
interactiveShell();
若对nodejs 的环境不了解,请参考
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。