How to get decimal remainder of two numbers divided? - c#

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;

Related

Errors in library fee code using multiple methods

I'm making a library program that asks for users to input the amount of books checked out and the amount of days they are over due. If its under or equal to 7 days they are charge 10 cents for each book over due after 7 days its 20 cents for each book. We are supposed to use more than one method and I get two errors:
Use of unassigned local variable 'totalCharge'
There is no argument given that corresponds to the required formal parameter 'daysOverdue' of Program.charge(double,double,double)'
I think I know what the first error means but I thought I already declared it a variable in the first line.
Here's the code so far:
static void Main(string[] args){
double totalCharge;
Console.WriteLine("Please enter the number of books checked out.");
double booksChecked = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of days they are
overdue.");
double daysOverdue = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your total charge for {0} days overdue is {1}.",
daysOverdue, totalCharge.ToString("C"));
Console.ReadKey();
totalCharge = charge();
}
private static double charge (double daysOverdue, double booksChecked,
double totalCharge)
{
if (daysOverdue <= 7)
{
return totalCharge = booksChecked * daysOverdue * .10;
}
else
{
return (booksChecked * .70) + (booksChecked) * (daysOverdue - 7)
* (.20);
}
}
}
}
Your code has a number of problems, which I'll review here. My corrections are at the end of this answer. I recommend putting your code and mine side by side and reviewing the differences carefully.
First, you cannot read the value out of a variable before you have assigned a value. You must assign something to it first.
You need to call charge(...) before printing out the value of totalCharge.
Second, you don't need to pass the value of totalCharge to your charge(...) method: it returns the total charge! So remove that parameter entirely.
Third, you need to pass parameters to the charge method.
Fourth, you had some formatting problems. Please review my code to see how I've formatted my code differently. If a line of code is continued onto the next line, use indentation to reflect this. According to C# conventions, function names should be capitalized.
Lastly, this isn't necessarily a problem, but it doesn't look 'right': in two places, you are assigning Convert.ToInt32(...) to a double. Why? Those should be integers.
static void Main(string[] args)
{
Console.WriteLine("Please enter the number of books checked out.");
double booksChecked = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of days they are overdue.");
double daysOverdue = Convert.ToInt32(Console.ReadLine());
// assign before printing out value
// pass the two parameters into the function
double totalCharge = Charge(daysOverdue, booksChecked);
Console.WriteLine("Your total charge for {0} days overdue is {1:C}.",
daysOverdue,
totalCharge);
Console.ReadKey();
}
private static double Charge(double daysOverdue, double booksChecked)
{
if (daysOverdue <= 7)
{
return booksChecked * daysOverdue * .10;
}
else
{
return (booksChecked * .70) + booksChecked * (daysOverdue - 7) * (.20);
}
}

multiplying and dividing from user input in 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");
}
}
}

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);

Error Reading User Input into Array

So I'm intentionally overcomplicating a homework assignment I was given because I was bored and wanted to learn more about c#. The original assignment is as follows:
"Compute the average of five exam scores ranging between 50 and 90. Declare and perform a compile-time initialization with the five values. Use a constant to define the number of scores. Display all scores and the average value formatted with no digits to the right of the decimal."
So I decided rather than just putting the 5 scores in, I'd allow the user to input them into an array and then calculate it from that.
Console.WriteLine("Enter 5 test scores between 50 and 90:");
int i = 0;
double total = 0;
double[] Scores;
Scores = new double[5];
while (i < 5)
{
Console.WriteLine("Input Score " + (i + 1) + ":");
String input = Console.ReadLine();
Scores[i] = double.Parse(input);
total += Scores[i];
i++;
}
Console.WriteLine("The average of the scores is: " + (total/5));
The issue is that the Scores[i] = double.Parse(input); is throwing an error saying that the input is in the wrong format. So the program won't even run to let me put IN an input, but it says the input format is incorrect.
Any suggestions? I'm probably missing something obvious.
EDIT: Ok, so what ended up working was changing the code to
Console.WriteLine("Input Score " + (i + 1) + ":");
Scores[i] = double.Parse(Console.ReadLine());
total += Scores[i];
i++;
Not sure what it actually changed but it seems to work pretty flawlessly!

Need help determining source of bug in small C# number to percentile conversion program

I'm fairly new to programming in general but have been working with Java for the past 2-3 months and decided to take a crack at C# on the side just for fun because I heard they were similar. The problem I'm having with this program, which is just a way for someone to convert an int to a percentage, is that it takes all my input correctly but the percentage always shows up as zero! For example, there are two input prompts: one that asks you for a number for converting and one that asks you what the number is out of. After both prompts the program displays correctly "Your percentage is: " and then just writes 0 no matter what numbers I use for input, help please!
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NumToPercentage
{
class Program
{
static void Main(string[] args)
{
int userScore, userTotalScore, userPercentage;
string userInput, userTotal;
Console.WriteLine("Welcome to the number to percentile conversion program!");
Console.WriteLine("Please enter your number here: ");
userInput = Console.ReadLine();
userScore = int.Parse(userInput);
Console.WriteLine("Please enter what the number is out of (i.e. 100, 42, 37, etc.): ");
userTotal = Console.ReadLine();
userTotalScore = int.Parse(userTotal);
userPercentage = (userScore/userTotalScore)*100;
Console.WriteLine("Your percentage is: " + userPercentage);
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
}
}
[/code]
The problem is integer math, it rounds towards zero.
1 divided by 100 is 0.
99 divided by 100 is 0.
199 divided by 100 is 1.
Convert at least one of the operands to a floating point type (double, float, decimal) when you perform your calculation.
double result = ((double)x / y) * 100;
If needed, you can always cast the result back to an integer if you are uninterested in the decimal places.
int finalPercent = (int)result;
userPercentage = (int)((double)userScore/userTotalScore)*100);
or
userPercentage = (userScore * 100) / userTotalScore;
int/int is an integer division and only returns the whole part which is always 0 for a percentage, which then multiplied by 0 equals... 0
(userScore/userTotalScore)*100;
dividing two integers will result in an integer value. It chops off the fraction.
Instead, do this
(int)( ( (double) userScore )/userTotalScore)*100 );
By utilizing type casting, you can get the result you are looking for.
You need to use decimals instead of ints. Integer division behaves different than floating point division.
Change your declarations to:
decimal userScore, userTotalScore, userPercentage;
And then later:
userScore = decimal.Parse(userInput);
And
userTotalScore = decimal.Parse(userTotal);
Because you declare your vars as int, you're performing an integer division.
You need to declare userPercentage as a double instead of int and cast the userScore and userTotalScore to double before performing the division.

Categories