[英]NodeJS - Read two numbers from input stream and print its sum to output stream
I'm trying to solve a task that reads: "Two whole numbers are defined in the standard input stream; each number is >= -32000 and <= 32000. Print the sum of these numbers to the standard output stream." I'm trying to solve a task that reads: "Two whole numbers are defined in the standard input stream; each number is >= -32000 and <= 32000. Print the sum of these numbers to the standard output stream." Input:
输入:
1
2
Output: Output:
3
My code is below:我的代码如下:
let total = 0;
let numbers_counter = 0;
process.stdin.on('data', data => {
numbers_counter++;
total += parseInt(data);
if (numbers_counter == 2) {
process.stdout.write(total.toString(), () => {
return process.exit()
});
}
})
process.stdin.on('end', () => {
process.stdout.write(total.toString(), () => {
return process.exit()
});
})
The problem is that I'm getting a 'wrong answer' response (I don't know how my code is tested, the only output I see is 'wrong answer')问题是我得到了“错误答案”响应(我不知道我的代码是如何测试的,我看到的唯一 output 是“错误答案”)
Any clue what needs to be changed?任何线索需要改变什么?
To begin with, this is enough:首先,这就足够了:
let total = 0;
let numbers_counter = 0;
process.stdin.on('data', data => {
numbers_counter++;
total += parseInt(data);
if (numbers_counter == 2) {
process.stdout.write(total.toString(), () => {
return process.exit()
});
}
})
And I think this is simpler:我认为这更简单:
let total = 0;
let numbers_counter = 0;
process.stdin.on('data', data => {
numbers_counter++;
total += parseInt(data);
if (numbers_counter == 2) {
process.stdout.write(total.toString());
process.exit();
}
})
Perhaps you will pass if you don't exit the process?如果您不退出该过程,也许您会通过?
As it turned out, both numbers were expected to be in one chunk of data事实证明,这两个数字都应该在一个数据块中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.