multiplying and dividing from user input in c# - c#

So this is the question.......
Context for code:
The longer you shower, the more water you use. But just how much? Even if you have a "low-flow" showerhead, odds are your shower spits out 1.5 gallons of water per minute. A gallon is 128 ounces, and so that shower spits out 1.5 × 128 = 192 ounces of water per minute. A typical bottle of water might be 16 ounces. So taking a 1-minute shower is akin to using 192 ÷ 16 = 12 bottles of water. Taking a 10-minute shower is like using 120 bottles of water. These numbers help put into perspective the amount of water being spent in a shower!
Write, in a file called water.c in your ~/workspace/pset1 directory, a program that prompts the user for the length of his or her shower in minutes (as a positive integer) and then prints the equivalent number of bottles of water (as an integer) per the sample output below, wherein underlined text represents some user’s input.
username#ide50:~/workspace/pset1 $ ./water
minutes: 10
bottles: 120
For simplicity, you may assume that the user will input a positive integer, so no need for error-checking (or any loops) this time! And no need to worry about overflow!
My current code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace console_water
{
class water_amount
{
static void Main(string[] args)
{
/*variable decleration*/
int multiply, divide;
int userInput = Console.Read();
multiply = 192;
divide = 16;
/*getting user input*/
Console.WriteLine("Length of shower in minutes:");
Console.Read();
userInput = multiply / divide;
Console.WriteLine("The amount of water used is:" + userInput);
}
}
}
But it's not working.

Try:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace console_water
{
class water_amount
{
static void Main(string[] args)
{
/*variable decleration*/
int multiply, divide;
int userInput;
multiply = 192;
divide = 16;
/*getting user input*/
Console.WriteLine("Length of shower in minutes:");
userInput = int.Parse(Console.ReadLine());
int numBottlesMinute = multiply / divide;
Console.WriteLine("The amount of water used is:" + userInput * numBottlesMinute);
}
}
}
userInput = int.Parse(Console.ReadLine()); this reads your shower length
int numBottlesMinute = multiply / divide; You should keep the number of bottles you use per liter in one variable(better constant ... but ok for your example)
Console.WriteLine("The amount of water used is:" + userInput * numBottlesMinute); Just print the result, number of bottles per minute * length of the shower.

You're not using Console.Read properly. Console.Read doesn't automatically store the user's input whenever they type into the console - you have to explicitly capture and store it if you want to use it.
If I were you, I'd use Console.ReadLine(), which takes all of the user's input up until they press enter.
To get the value of multiply, you could do something like:
Console.WriteLine("Minutes: ");
int input = int.Parse(Console.ReadLine());
Note that you need to do int.Parse on the user's input, as Console.ReadLine() returns a string.

public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("enter 1 no.");
float i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter 2 no.");
float j = Convert.ToInt32(Console.ReadLine());
if (j % i == 0)
{
Console.WriteLine("devide no.is {0}", j);
Console.ReadLine();
}
else
{
Console.WriteLine("wrong input");
}
}
}

Related

Could someone explain why Converting to int and using read line instead of Read fixed my issue?

So previous I was having a ton of trouble with finding the difference between a randomly generated number and user input. I did a little search and found that I couldn't use Console.Read(); and that I actually had to use this int guess = Convert.ToInt32(Console.ReadLine()); While playing around with it i accidentally made it Convert.ToInt32(Console.Read()); which was in turn making the math completely wrong. Apologies if I'm not explaining myself effectively I'm new to coding and this was meant to be something to learn from. Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Would you like to play the guessing game?");
string input = Console.ReadLine();
if (input.Equals("yes"))
{
Console.WriteLine("Alright! The rules are simple, i'll think of a number and you guess it!");
Console.WriteLine("Alright enter your guess: ");
int guess = Convert.ToInt32(Console.ReadLine());
Random rand = new Random();
int answer = rand.Next(1,11);
if (rand.Equals(guess))
{
Console.WriteLine("Congratulations you guessed correctly!");
}
else
{
Console.WriteLine("Aww you were so close! I guessed " + answer);
int difference = guess - answer;
Console.WriteLine("you were only " + Math.Abs(difference) + " away");
}
} else
{
Console.WriteLine("Closing application...");
Thread.Sleep(1000);
Environment.Exit(0);
}
}
}
}
Console.Read()
Returns you the ascii value of a single character being input.
For example, entering 'A' would return 65. See here for a list of ascii codes. Note that the ascii value for 1 is actually 49.
Convert.ToInt32(Console.ReadLine());
Reads the entire line and tries to convert it to an integer.
Console.Read() will grab just one character and Console.ReadLine() takes the whole line or everything the user types until it found the "Enter" key pressed.
Becuase Console.Read reads in characters from the console. It returns, as an integer. So when you enter "yes" the output will be
121 = y
101 = e
115 = s
13 =
10 =
The final two characters (13 and 10) are equal to the Windows newline.

How to get decimal remainder of two numbers divided?

So I am trying to make a script where the user inputs the number of miles they need to travel and the miles per hour they are traveling and the script outputs the hours and minutes leftover that they must travel. I've been trying to use % to find the remainder of the miles traveled/MPH but it outputs the wrong number. Is there anyway to only get the decimal from two divided numbers? For example, if I do 100/65 I get the output of about 1.538, I want to only use the 0.538. But when I use 100%65 I get 35. Here is my current script for reference:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimeCalculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Travel Time Calculator");
string answer;
//creates variable for the answer
do
//creates loop to continue the application
{
string grade;
//Console.WriteLine(100-(int)((double)100/65)*65);
Console.WriteLine(" ");
Console.Write("Enter miles: ");
Decimal val1 = Convert.ToDecimal(Console.ReadLine());
//converts input to decimal allowing user to use decimals
Console.Write("Enter miles per hour: ");
Decimal val2 = Convert.ToDecimal(Console.ReadLine());
//converts input to decimal allowing user to use decimals
Console.WriteLine(" ");
Console.WriteLine("Estimated travel time");
Console.WriteLine("Hours: " + (((int)val1 / (int)val2)));
//converts values to integers and divides them to give hours traveled
//double floor1 = Math.Floor(((double)val1/(double)val2));
Console.WriteLine("Minutes: " + (Decimal.Remainder((decimal)val1, (decimal)val2)));
//converts values to double and gets the remainder of dividing both values to find minutes
Console.WriteLine();
//enters one line
Console.Write("Continue? (y/n): ");
answer = Console.ReadLine();
//the string is equal to what the user inputs
Console.WriteLine();
}
while (answer.ToUpper() == "Y");
//if y, the application continues
}
}
100/65 is an integer division. What you need is
double d = (100d / 65) % 1;
This will give you 0.53846153846153855
If you want hours and minutes from the initial values then this should do it for you (you may need some explicit casts in there, this is untested)
var result = va1 / val2;
var hours = Math.Floor(result);
var minutes = (result - hours) * 60;

C# Variable int assumes a different value

I'm trying to create a simple program to calculate an average. The user should enter a positive number, then I create a loop to sum from 0 to the number entered. Then the average is the total divided by the number entered.
Problem: When I enter a number, for example, 10, the variable becomes 58. To any value that I enter, it always adds 48. Anyone have a clue about this issue?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace inClass1
{
class Loops
{
static void Main(string[] args)
{
int total = 0;
int num;
Console.Write("Enter a positive number: ");
num = Convert.ToInt32(Console.Read());
for (int i = 0; i <= num; i++)
{
total = total + i;
}
double average = total / (double)num;
Console.WriteLine("The average is = " + average);
Console.ReadLine();
}
}
}
It's because Console.Read method reads the first char and returns its ASCII value. And it only reads one char, so you can't read more than one number at the same time. To fix that just use Console.ReadLine to take a string as input:
um = Convert.ToInt32(Console.ReadLine());
In case where the user inputs an invalid number this will fail. To prevent that you can look into int.TryParse method.
The problem is that you are using Console.Read.
That method returns a int, not a string. That int is the Unicode character code of the read character. The overload of Convert.ToInt32 that takes a int looks like this:
public static int ToInt32(int value) {
return value;
}
(Reference Source)
Which means that its just returning the passed value (instead of parsing). Unicode '1' is the number 49.
Instead, use Console.ReadLine which in addition to getting the whole input (not just the first character) will return a string, so that int.Parse is called on it instead of casting when you use Convert.ToInt32.

Allow only numbers to be inserted & transform hours to minutes to calculate gold/min - UPDATED

I have an application that calculates your gold per minute farmed.
I want to make an error report that wouldn't allow you to insert any text in the console input where yous hould insert the time and gold(as shown in code below) and show some error message if you do and let you redo the insertion (some sort of loop or if/else thing ...)
Hope i made my self clear,thou I'm new to this... so i hope you understand.
Here is my code so far :
-------------------------------//////////
Update on question because i didn't want to make a new question for the same code :
How do i transform in this code my hours into minutes,the float calculation of 1.2 hours will calculate into 72 minutes not 80.(i've put comment below in code where the problem is)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YourGold
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to YourGold App! \n------------------------");
Console.WriteLine("Inesrt your gold: ");
int gold = int.Parse(Console.ReadLine());
Console.WriteLine("Your gold is : " + gold);
Console.WriteLine("Inesrt your time(In Hours) played: ");
float hours = float.Parse(Console.ReadLine());
int minutes = 60;
float time = (float)hours * minutes; // Here the calculation are wrong...
Console.WriteLine("Your total time playd is : " + time + " minutes");
float goldMin = gold / time;
Console.WriteLine("Your gold per minute is : " + goldMin);
Console.WriteLine("The application has ended, press any key to end this app. \nThank you for using it.");
Console.ReadLine();
}
}
}
Thank you!
Instead of using int.Parse, you can use int.TryParse, and print a message:
int gold;
while(!int.TryParse(Console.ReadLine(), out gold))
{
Console.WriteLine("Please enter a valid number for gold.");
Console.WriteLine("Inesrt your gold: ");
}
This allows you to re-prompt and handle errors correctly.
In console application you can't control text input (no keypressed event to handle).
This could be a solution
Console.WriteLine("Inesrt your gold: ");
int gold;
while(!int.TryParse(Console.ReadLine(),out gold)){
Console.WriteLine("Please provide a valid gold value");
}
Console.WriteLine("Your gold is : " + gold);

Random number in c# which should be exactly random every time?

i am trying to generate random number for my mental math quiz game. But i think i am doing something wrong.Please help me to correct my code.Please try to include some sort of explanation, why my code is incorrect. Thanks in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MindTraining
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the digits of first number ");
int a=int.Parse(Console.ReadLine());
Console.WriteLine("Enter the digits of second number");
int b = int.Parse(Console.ReadLine());
Random RandomClass = new Random(DateTime.UtcNow.Second);
int RandomNumber = RandomClass.Next(10^(a-1), 10^a);
Console.WriteLine(RandomNumber);
}
}
}
What i am trying to achieve is , I want user to enter number of digits in number a and number of digits in number b
Then program would generate random number, say user entered 2 for a ,then program have to generate numbers between 0 to 10(Random Number, Every time different)
if user entered 3 for a, then between 10 to 100,
Similar thing for b, and then calculating product.Number should not repeat more than 2 times, during program run time.
Ok, i changed my code to
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MindTraining
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the digits of first number ");
int a=int.Parse(Console.ReadLine());
Console.WriteLine("Enter the digits of second number");
int b = int.Parse(Console.ReadLine());
Random RandomClass = new Random(DateTime.UtcNow.Second);
double num1=Math.Pow(10,a-1);
double num2=Math.Pow(a,1);
int num3 = Convert.ToInt32( num1);
int num4=Convert.ToInt32(num2);
int RandomNumber = RandomClass.Next(num3,num4);
Console.WriteLine(RandomNumber);
}}
// But still not getting result, I throws error,
This one worked!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MindTraining
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the digits of first number ");
int a=int.Parse(Console.ReadLine());
Console.WriteLine("Enter the digits of second number");
int b = int.Parse(Console.ReadLine());
Random RandomClass = new Random();
double num1=Math.Pow(10,(a-1));
double num2=Math.Pow(10,(a));
int num3 = Convert.ToInt32( num1);
int num4=Convert.ToInt32(num2);
int RandomNumber = RandomClass.Next(num3,num4);
Console.WriteLine(RandomNumber);
}
}
}
^ is not a raise to the power operator in c#.
Use Math.Pow for this.
The ^ operator in C# means "exclusive or" (XOR), not exponentiation. Read about it here: http://www.dotnetperls.com/xor . Try Math.Pow instead.
is there any reason you want to use a seed value that is so limited? Why not use
Random RandomClass = new Random();
which takes a default time based seed value for your object?
Also, use Math.pow(base,exp) to calculate the range for your Random.next() calls as:
int RandomNumber = RandomClass.Next((int)Math.Pow(10,(a-1)), (int)Math.Pow(10,a));
In your code, the error occurs because,
double num2=Math.Pow(a,1);
returns a itself. So, your maxvalue in the Random.next() is lower than your minvalue, which is logically incorrect. This is the error, I got from running your code, that is apart from the fact that you are missing a closing brace at the end.
Also, you must realise that there is no such thing as a perfectly random number generator. All these are pseudo-random generators. They follow the normal distribution of numbers on the number line. So, to say that a number will not be generated more than twice in one execution is not feasible unless you store all the numbers generated and keep checking against them. This should be a last resort, only is case of dire requirements.
While generating a TRULY random number you cannot suppose that the number is different all the time,hope you got the point. So you need to additionally make sure that the number is different each time.

Categories