在nodejs中交换两个数字不知道为什么会遇到运行时错误

发布于 2025-01-30 22:48:23 字数 1003 浏览 5 评论 0原文

我正在尝试编写一个代码,在nodejs中交换两个数字,但我遇到了运行时错误。 当我第二次已保存文件时,再次遇到相同的错误。我认为这与以某种方式关闭文件有关。有人有什么想法吗?我的代码如下 -

function swap(num1 , num2){             
    let temp = num1;
    num1 = num2;
    num2 = temp;
    return; 
}

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

function main() {
    let t = parseInt(readLine());
    while(t-->0){
        const arr = readLine().replace(/\s+$/g, '').split(' ');
        var num1 = (Number)(arr[0]);
        var num2 = (Number)(arr[1]);
        var res = swap(num1 , num2) ; 
        console.log(res[0] , res[1]);
    }
}

I'm trying to write a code swapping two numbers in nodejs but I'm getting runtime error.
When I run a second time when the file was saved already then again getting same error. I think this is related to closing the file somehow. Has anyone any ideas? My code is as follows -

function swap(num1 , num2){             
    let temp = num1;
    num1 = num2;
    num2 = temp;
    return; 
}

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

function main() {
    let t = parseInt(readLine());
    while(t-->0){
        const arr = readLine().replace(/\s+$/g, '').split(' ');
        var num1 = (Number)(arr[0]);
        var num2 = (Number)(arr[1]);
        var res = swap(num1 , num2) ; 
        console.log(res[0] , res[1]);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁吢 2025-02-06 22:48:23

您没有从交换函数中返回,因此res == undefined

function swap(num1, num2) {
  return [num2, num1];
}

这应该解决

You're not returning from your swap function, so res == undefined.

function swap(num1, num2) {
  return [num2, num1];
}

This should fix that

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文