Jump to content

Got this problem

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Haaris

Haaris

    Newbie

  • Members
  • Pip
  • 2 posts
Hi there,

I am new to c#, I have written this code that calculates number of days out of number of hours. But the problem is when I input 25 hours, the value in the hours field is saved as 50 i.e. double of the actually entered value. Can someone help me about this.


  int hours, numberOfDays = 0;

            Console.WriteLine("Please enter number of hours => ");

            hours = Convert.ToInt32(Console.Read());

            numberOfDays = hours/24;

            int hoursLeft = hours%24;


            Console.WriteLine("Number of days => {0}", numberOfDays);

            Console.WriteLine("Number of hours left => {0}", hoursLeft);

            Console.ReadKey();


#2
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Are you saying that this line:

hours = Convert.ToInt32(Console.Read());

Is causing 25 to be interpreted as 50? I don't see how that is possible from your code. How did you arrive at the conclusion?

#3
TcM

TcM

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 11,147 posts
Try int.Parse instead Convert.ToInt32 .. should not make a difference.. but just to make sure.

#4
njr1489

njr1489

    Learning Programmer

  • Members
  • PipPipPip
  • 70 posts
Normally, I do this:
hours = int.Parse(Console.ReadLine());

I used to convert strings this way though:

string response;

int hours;

response = Console.ReadLine();

hours = Convert.ToInt32(hours);


This is all assuming if the source of your problem is when the conversion takes place...

EDIT: Just to note, this is what the documentation for the Console.Read method says:
"Reads the next character from the standard input stream."
I would use Console.ReadLine just in case.

#5
scottk

scottk

    Learning Programmer

  • Members
  • PipPipPip
  • 35 posts
Use the Console.Read() returns an int value so you don't need to call Convert.ToInt32(). Change your code to use Console.ReadLine() and life will be good.

    public static void Main(string[] args)

    {

      int i = Console.Read();

      System.Diagnostics.Debugger.Break(); //i = 50 if you key "25" then <enter>

    }