高尔夫回球输出逻辑问题

问题描述 投票:0回答:3

大家好,我正在尝试为 java 类做一个硬件问题,但我在理解逻辑时遇到了一些困难。这是他们问我的问题:

高尔夫分数记录了将球击入洞中所用的击球次数。不同洞的预期击球数有所不同,称为标准杆(即 3、4 或 5)。每个分数都有一个可爱的名字,基于与标准杆相比的实际击球数。如果杆数比标准杆少两杆,则返回“Eagle”。如果杆数比标准杆少一杆,则返回“Birdie”。如果 par 与笔划完全匹配,则返回“Par”。如果杆数比标准杆多一杆,则返回“柏忌”。如果 par 不是 3、4 或 5,则返回“错误”。

这是我的代码:

public class Main {
   
   public String golfScore(int par, int strokes){
      
      if(strokes <= par - 2){
         return "Eagle";
      }
      else if(strokes <= par -1){
         return "Birdie";
      }
      else if(strokes == par){
         return "Par";
      }
      else if(strokes > par + 1){
         return "Bogey";
      }
      else{
         return "Error";
      }
   }
   
   // this method not used but needed for testing
   public static void main(String[] args) {
   }
}

当我运行结果时,除了最后一次测试之外,所有结果都是正确的。

但是这个逻辑对我来说没有意义,因为它应该使我的 if 语句无效。因为 1 > 2 + 1 为 false,因此应该输出错误。为什么我的程序输出柏忌?

java logic
3个回答
1
投票

解决了!感谢克里斯·福伦斯!

if ((par != 3) && (par != 4) && (par != 5)){
     return "Error";
  }
  else if(strokes <= par - 2){
     return "Eagle";
  }
  else if(strokes <= par -1){
     return "Birdie";
  }
  else if(strokes == par){
     return "Par";
  }
  else{
     return "Bogey";
  } 

}


0
投票

如果有人正在寻找这个问题的解决方案,但用 C++ 编写,这里就是。

#include <iostream>
using namespace std;

int main() {

    int par;
    int strokes;

    cin >> par >> strokes;

    if ((par != 3) && (par != 4) && (par != 5)){
        cout << "Error" << endl;
    }
    else if (strokes == par - 2){
        cout << "Eagle" << endl;
    }
    else if (strokes == par - 1){
        cout << "Birdie" << endl;
    }
    else if (strokes == par){
        cout << "Par" << endl;
    }
    else if (strokes == par + 1){
        cout << "Bogey" << endl;
    }
    else{
        cout << "None" << endl;
    }


    return 0;
}

0
投票

这是我用 python 编写代码的方式:

    num_stro = int(input())
num_par = int(input())
list_anim = ['Eagle','Birdie', 'Par', 'Bogey']
if num_stro + 2 == num_par:
    str_anim = 'Eagle'
elif num_stro + 1 == num_par:
    str_anim = 'Birdie'
elif num_stro == num_par:
    str_anim = 'Par'
elif num_stro - 1 == num_par:
    str_anim = 'Bogey'
else:
    str_anim = ''

if  str_anim in list_anim and 3<=num_par<=5:
    if str_anim == 'Eagle':
        print(f'Par {num_par} in {num_stro} strokes is {str_anim}')
    elif str_anim == 'Birdie':
        print(f'Par {num_par} in {num_stro} strokes is {str_anim}')
    elif str_anim == 'Par':
        print(f'Par {num_par} in {num_stro} strokes is {str_anim}')
    elif str_anim == 'Bogey':
        print(f'Par {num_par} in {num_stro} strokes is {str_anim}')
else:
    print(f'Par {num_par} in {num_stro} strokes
© www.soinside.com 2019 - 2024. All rights reserved.