在Bash中查找余数。

huangapple go评论63阅读模式
英文:

Find remainder in bash

问题

以下是您提供的代码部分的中文翻译:

#!/bin/bash
read T
var0=0

while [[ "$var0" -lt "$T" ]]
do

read A B

echo $(( A % B ))

(( var0++ ))
done

如果您需要关于代码的任何进一步解释或帮助,请随时提问。

英文:

A codechef problem:

> Write a program to find the remainder when an integer A is divided by an integer B.
>
> ##### Input
>
> The first line contains an integer T, the total number of test cases. Then T lines follow, each line contains two Integers A and B.
>
> ##### Output
>
> For each test case, find the remainder when A is divided by B, and display it in a new line.
>
> ##### Constraints
>
> * 1 ≤ T ≤ 1000
> * 1 ≤ A,B ≤ 10000

This is my solution. It works with the sample numbers but when I submit it it fails a test. I'm pretty sure the code is correct. What might the problem be?

#!/bin/bash
read T
var0=0

while [[ "$var0" < "$T" ]]
do

read A B

echo $(( A % B ))

(( var0++ ))
done

答案1

得分: 2

你的代码在特定条件下运行良好,但没有在这里进行解释。我复制了它,保存为rem.bash,更改了权限以使其可执行,然后运行它。以下是会话结果:

$ rem.bash
3
1 3
1
2 3
2
4 3
1

第一个3是运行操作的次数。然后我输入:1 3。余数输出为1。在第三次迭代中,我输入:4 3。余数为1。循环退出,程序终止。

要使其适用于所有输入,请更改while行为

while ((var0 < t))

在bash算术中,((和))之间的内容,您不需要使用$来引用变量。您还可以使用标准的关系运算符。

英文:

Your code works fine under specific conditions not explained here. I copied it, saved it to rem.bash, changed the permission to make it executable, and ran it. The following is the session result:

$ rem.bash
3
1 3
1
2 3
2
4 3
1

The first 3 is the number of times to run the operation. I then entered: 1 3. The remainder is output as 1. On the third iteration, I entered: 4 3. The remainder is 1. The loop exited, and the program terminated.

To make it work for all inputs, change the while line to

while ((var0 &lt; t))

In bash arithmetic, stuff between (( and )), you don't need $ to dereference the variable. You can also use standard relational operators.

huangapple
  • 本文由 发表于 2023年3月31日 04:08:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定