0

my code:

static int klassenBreite(int histMin, int histMax, int klassen) {
    int abstand =(int) ((histMax- histMin)/klassen +0.5);

    return abstand;
}

if I run

klassenBreite(100,200,8);

I should get 13, but my program calculates it to be 12. I really don't know what went wrong, if I do it by hand it gives 13. I am not sure if I'm rounding it correctly.

Cherry
  • 81
  • 2
  • 10
  • I am unfamiliar with klassenBreite, but is that integer division intentional? Because my guess is it's not... – Socratic Phoenix Oct 26 '17 at 15:42
  • Do you know what `int` stands for? – tnw Oct 26 '17 at 15:42
  • it's a method i have created myself – Cherry Oct 26 '17 at 15:53
  • I still haven't got an answer on my question, why would you mark it as a duplicate when it's not at all a duplicate? @kayaman – Cherry Oct 26 '17 at 15:54
  • Well, I see integer division -> I close it as integer division. I see `NullPointerException`, I close it as "What is a NPE and how do I fix it". So is that integer division in your code intentional? – Kayaman Oct 26 '17 at 15:55
  • yes, but I don't understand why it gives back 12 when it should return 13. I add 0.5, which would give 13... Where do you see a NullPointerException? thanks! – Cherry Oct 26 '17 at 15:57
  • Are you **really** sure that **integer** division is intentional? The concept which is discussed in detail in the duplicate? – Kayaman Oct 26 '17 at 15:58
  • @Cherry It is blatantly a duplicate. Read it. – tnw Oct 26 '17 at 15:58
  • I have read it. I have a question: if I add a double to an integer, do I get a double or and integer? – Cherry Oct 26 '17 at 16:05
  • btw it worked when I converted one to double but I don't understand why – Cherry Oct 26 '17 at 16:05
  • Because integer division gives you an integer result, so `(200-100)/8` is `12`. Add `0.5`, cast to int and you still have `12`. Next time **read** the duplicate before saying "it's not a duplicate". – Kayaman Oct 26 '17 at 16:24

0 Answers0