一个检查数字是否存在于序列中的程序产生了意外的结果。

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

A program to check if a number is present in series gives unexpected result

问题

以下是翻译好的代码部分:

public class Main {
    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        double n;
        int k;
        int T = sc.nextInt(); // 用户提供的系列次数
        while (T != 0) {
            T -= 1;
            int A = sc.nextInt(); // 等差数列的第一个项
            int B = sc.nextInt(); // 要检查是否存在于系列中的数字
            int C = sc.nextInt(); // 公差
            if (A == B) {
                System.out.print("YES");
            }
            n = (((B - A) / C) + 1); // 如果这个公式正确,那么当B存在于系列中时n应该是整数
            // 或者当B不在系列中时n应该是浮点数
            k = (int) n;
            if (k == n)
                System.out.println("YES");// 即使当B不在系列中时也会打印"YES"
            else
                System.out.println("NO");
        }
    }
}
英文:

Program to check if a given number is present in an arithmetic progression series. User provides T, which is the number of a series that the user also provides.

User provides A, 1st number of series, B, the number to check if present in series and C, the common difference.

The code runs, but won't submit online(shows runtime error). Also, in each case the output is "YES".

public class Main {
    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        double n;
        int k;
        int T = sc.nextInt(); //number of times series will be given by user.
        while (T != 0) {
            T -= 1;
            int A = sc.nextInt(); //1st term of the AP series
            int B = sc.nextInt(); //to check if this number(B) appears in the series
            int C = sc.nextInt(); //common difference
            if (A == B) {
                System.out.print("YES");
            }
            n = (((B - A) / C) + 1); // if this formula is right then n should be 
            //an integer when B is present in series
            //or it n should be a float number if B is not in the series
            k = (int) n;
            if (k == n)
                System.out.println("YES");// even when B is NOT in series, "YES" is printed
            else
                System.out.println("NO");
        }
    }
}

答案1

得分: 1

Java在整数相除时会舍弃余数,因此尽管将 n 声明为 double,它始终将具有整数值。您可以用 (1.0 * C) 替换 C 以执行浮点数除法,或者使用取模运算符 % 来完全避开这个问题。

英文:

Java discards the remainder when dividing integers, so despite declaring n as a double, it will always have an integer value. You could replace C with (1.0 * C) to force floating-point division, or use the modulo operator % to sidestep the issue entirely.

huangapple
  • 本文由 发表于 2020年9月23日 06:04:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64018282.html
匿名

发表评论

匿名网友

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

确定