I am trying to figure out final price based on wage multiplied by hours.
Here is my code
Why if the hours are 02:30:00 and the wage: $14 is my total 2?
TimeSpan duration = TimeSpan.Parse("02:30:00");
int wage = 14;
var result = (duration.Hours + (duration.Minutes / 60) * wage);
First, the expression is actually evaluated as:
duration.Hours + ((duration.Minutes / 60) * cleaner.Price)
Second, you are doing integer division, so 30/60 will result in 0, leaving you with the value 2 i.e. the Hours part.
To fix the issue, you can do something like the below:
(duration.Hours + ((decimal)duration.Minutes / 60)) * 14;
Alternatively, you can skip this component-wise calculation, and just use the TotalHours property instead:
duration.TotalHours * 14
Related
This question already has answers here:
C# Bug or Something Wrong [duplicate]
(4 answers)
Closed 6 years ago.
I am developing an app for a client. It should get some inputs from the console, like total meal price; plus, the second line should ask for the tip percentage. The third would ask for taxPercent.
I have the following code, but it fails one of two test cases.
When I enter 15.50 for mealCoast, 15 percent for tip and 10% for tax, it passes the test case. However, if I enter 12.00 for mealCost, 20 for tip% and 8 for tax percent, it fails to meet the test case requirements.
Here you can see my code sample.
double mealCoast = double.Parse(Console.ReadLine());
int tipPercent = int.Parse(Console.ReadLine());
int taxPercent = int.Parse(Console.ReadLine());
//Calculating %
tipPercent = Convert.ToInt16(mealCoast) * (tipPercent) / 100;
taxPercent = Convert.ToInt16(mealCoast) * (taxPercent) / 100;
int totalCast = Convert.ToInt16(mealCoast) + tipPercent + taxPercent;
Console.WriteLine("The total meal cost is {0} dollars.", totalCast);
Console.ReadKey();
A couple of possible issues:
Firstly, beware of the integer division. It basically means that if you divide int data type by int data type, you will get int result. Note that you use int all over the places, which is not a good practice - in your application, likely you don't want that. But rather you want to be precise in your money-involved computation. Thus, I suggest to use double - or better - decimal for your data computation
Secondly, beware of the non-convertible string to the respective number data type (be it int or floating point like double). Don't use Parse, but use TryParse to ensure the input is convertible.
By using correct data type and correct way to process the data, you would already half-way accomplishing your goals. Putting them into code, this is how it may look like:
decimal mealCoast, tipPercent, taxPercent; //use decimal, probably is best
bool mealCoastResult = decimal.TryParse(Console.ReadLine(), out mealCoast);
bool tipPercentResult = decimal.TryParse(Console.ReadLine(), out tipPercent); //use TryParse
bool taxPercentResult = decimal.TryParse(Console.ReadLine(), out taxPercent);
//Input checking, check any parsing error
if (!mealCoastResult || !tipPercentResult || !taxPercentResult){
//do some error handlers
return; //probably don't continue is good
}
//you could also put some while loop
//Calculating %
tipPercent = mealCoast * tipPercent / 100;
taxPercent = mealCoast * taxPercent / 100;
decimal grandTotal = mealCoast + tipPercent + taxPercent;
Console.WriteLine("The total meal cost is {0} dollars.", grandTotal);
Console.ReadKey();
however second case 12.00 for mealPrice , 20 for tip and 8 for tax fails to produce required output output should be 15 usd it prints 14 usd strange thing taxtPercent variable become 0
Let's have a look at your code for the example:
double mealCoast = double.Parse(Console.ReadLine()); // mealCoast = 12.
int tipPercent = int.Parse(Console.ReadLine()); // tipPercent = 20
int taxPercent = int.Parse(Console.ReadLine()); // taxPercent = 8
//Calculating %
// Convert.ToInt16(mealCoast) will give you 12
// you are using integer division here, no digits preserved after period.
tipPercent = Convert.ToInt16(mealCoast) * (tipPercent) / 100; // 12 * 20 / 100 = 2
taxPercent = Convert.ToInt16(mealCoast) * (taxPercent) / 100; // 12 * 8 / 100 = 0
// 12 + 2 + 0 = 14
int totalCast = Convert.ToInt16(mealCoast) + tipPercent + taxPercent; // 14
Console.WriteLine("The total meal cost is {0} dollars.", totalCast);
Console.ReadKey();
/ operator is integer division if its operands are of integer types. It will truncate all the decimal digits after period. This also does not depend on the type of the variable you are assigning result at. Take a look at decimal or double data types.
I'm failing to understand why this will only return 0 or 100.
decimal TotalUptimePercent;
TotalUptimePercent = (uptime / (uptime + downtime)) * 100;
MessageBox.Show("Uptime: " + TotalUptimePercent.ToString());
I've tried using double instead of decimal but that didn't work either.
I did look over the site and found some other posts about percentages which recommended using decimal, but isn't working for me.
If uptime and downtime are int or alike, try
double TotalUptimePercent = (uptime / (uptime + (double)downtime)) * 100;
See / Operator:
When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2.
This might not be the correct place for this, so apologies in advance if it isn't.
My situation - I need to come up with a simple formula/method of giving it an hour E.g. 13, 15, 01 etc, and based on that number, the method will return the 'approx' temperature for that particular time.
This is very approximate and it will not use weather data or anything like that, it will just take the hour of the day and return a value between say -6 deg C > 35 deg C. (very extreme weather, but you get the idea.)
This is the sort of examples I would like to know how to do:
Just as a note, I COULD use an ugly array of 24 items, each referencing the temp for that hour, but this needs to be float based - e.g. 19.76 should return 9.25 deg...
Another note: I don't want a complete solution - I'm a confident programmer in various languages, but the maths have really stumped me on this. I've tried various methods on paper using TimeToPeak (the peak hour being 1pm or around there) but to no avail. Any help would be appreciated at this point.
EDIT
Following your comment, here is a function that provides a sinusoidal distribution with various useful optional parameters.
private static double SinDistribution(
double value,
double lowToHighMeanPoint = 0.0,
double length = 10.0,
double low = -1.0,
double high = 1.0)
{
var amplitude = (high - low) / 2;
var mean = low + amplitude;
return mean + (amplitude * Math.Sin(
(((value - lowToHighMeanPoint) % length) / length) * 2 * Math.PI));
}
You could use it like this, to get the results you desired.
for (double i = 0.0; i < 24.0; i++)
{
Console.WriteLine("{0}: {1}", i, SinDistribution(i, 6.5, 24.0, -6.0, 35.0));
}
This obviously discounts environmental factors and assumes the day is an equinox but I think it answers the question.
So,
double EstimatedTemperature(double hour, double[] distribution)
{
var low = Math.Floor(hour);
var lowIndex = (int)low;
var highIndex = (int)Math.Ceiling(hour);
if (highIndex > distribution.Count - 1)
{
highIndex = 0;
}
if (lowIndex < 0)
{
lowIndex = distribution.Count - 1;
}
var lowValue = distribution.ElementAt(lowIndex);
var highValue = distribution.ElementAt(highIndex);
return lowValue + ((hour - low) * (highValue - lowValue));
}
assuming a rather simplistic linear transition between each point in the distibution. You'll get erroneous results if the hour is mapped to elements that are not present in the distribution.
For arbitrary data points, I would go with one of the other linear interpolation solutions that have been provided.
However, this particular set of data is generated by a triangle wave:
temp = 45*Math.Abs(2*((t-1)/24-Math.Floor((t-1)/24+.5)))-10;
The data in your table is linear up and down from a peak at hour 13 and a minimum at hour 1. If that is the type of model that you want then this is really easy to put into a formulaic solution. You would just simply perform linear interpolation between the two extremes of the temperature based upon the hour value. You would have two data points:
(xmin, ymin) as (hour-min, temp-min)
(xmax, ymax) as (hour-max, temp-max)
You would have two equations of the form:
The two equations would use the (x0, y0) and (x1, y1) values as the above two data points but apply them the opposite assignment (ie peak would be (x0, y0) on one and (x1, y1) in the other equation.
You would then select which equation to use based upon the hour value, insert the X value as the hour and compute as Y for the temperature value.
You will want to offset the X values used in the equations so that you take care of the offset between when Hour 0 and where the minimum temperature peak happens.
Here is an example of how you could do this using a simple set of values in the function, if you wish, add these as parameters;
public double GetTemp(double hour)
{
int min = 1;
int max = min + 12;
double lowest = -10;
double highest = 35;
double change = 3.75;
return (hour > max) ? ((max - hour) * change) + highest : (hour < min) ? ((min - hour)*change) + lowest : ((hour - max) * change) + highest;
}
I have tested this according to your example and it is working with 19.75 = 9.6875.
There is no check to see whether the value entered is within 0-24, but that you can probably manage yourself :)
You can use simple 2 point linear approximation. Try somthing like this:
function double hourTemp(double hour)
{
idx1 = round(hour);
idx2 = idx1 + 1;
return (data[idx2] - data[idx1]) * (hour - idx1) + data[idx1];
}
Or use 3,5 or more points to get polynom cofficients with Ordinary Least Squares method.
Your sample data similar to the sin function so you can make sin function approximation.
I can't figure out how to recursively calculate the rate of return on an investment, where the principal is unknown, and only the rates and the duration of the rates are known.
For example, if I had an investment for 2 years at 10% (or 0.1), the RoR would equal 0.21 (or 21%). This is calculated non-recursively as,
0.21 = 2 * 0.1 + (0.1 ^ 2)
// or
ror = duration * rate + (rate ^ duration)
Since I may not want to only know the final calculation, but the intermittent years of that investment, I must do this recursively (e.g. if the duration is 5 years, I want to know what the rate of return is after the first year, the second year and so on).
Since this is an algorithm, C# isn't required, but that is what I will be programming it in.
The easiest to calculate recursively is 1.0+RoR:
double calculateRateOfReturnPlus1(double rate, int periods) {
if (periods == 0)
return 1.0;
return (1.0 + rate) * calculateRateOfReturnPlus1(rate, periods - 1);
}
This returns 1.21 for rate=0.1, periods=2 and 1.331 for rate=0.1, periods=3. You can then subtract 1.0 to obtain pure RoR. Alternatively, you can compute RoR directly like this:
double calculateRateOfReturn(double rate, int periods) {
if (periods == 0)
return 0.0;
return (1.0 + rate) * (calculateRateOfReturn(rate, periods - 1) + 1.0) - 1.0;
}
Also, you can calculate RoR iteratively like this:
double calculateRateOfReturn(double rate, int periods) {
double RoR = 1.0;
for (int i = 0; i < periods; i++) {
RoR = RoR * (1.0 + rate);
}
return RoR - 1.0;
}
The last two functions return 0.21 for rate=0.1, periods=2 and 0.331 for rate=0.1, periods=3.
In practice one would simply rely on the Math.Pow() function:
double calculateRateOfReturn(double rate, int periods) {
return Math.Pow(1.0+rate, periods) - 1.0;
}
A LINQ version:
double rate = 0.1;
int totalYears = 5;
var results = Enumerable.Range(1, totalYears).Select(i => new { Year = i, RoR = Math.Pow(1 + rate, i) - 1 });
This gives you the rate of return for every year within the period.
I've done similar "modelling" in a spreadsheet, and the easiest way to do this is to calculate the compound interest for every year, and then in another column calculate the difference between successive years.
If you still want to use recursionto calculate yearly (or any other period) you could input the result of the calculation (starting with 1) as the principal for the next period.
So period 0 "rate" would be 1, then period 1 would be 1.1, period 2 would be 1.21 etc.
I have two values one with a decimal value
and another value with a value which will calculate the percentage of that decimal value
for example:
60 % of 10 = 6
decimal value1 = 10;
decimal percentage = 60;
textbox1.text = ("mathsum here").toString();
How would you calculate this value using the decimal value and value containing the percentage value?
number * percentage / 100
so
10 * 60 / 100 = 6
Maybe it will help you to think of it in this way.
6
-- = .6 (or equivalent to your 60%)
10
In your example you'd like to know how to calculate the numerator (the 6) so assign a variable to it. Let's use X.
X
-- = .6
10
.. and solve for X by multiplying both sides by 10 (in your case).
X * 10 = .6 * 10
------
10
X = .6 * 10
From this I hope you can see that you can take your percentage value and multiply it by your 'decimal' value.
Note that in order to get the .6 you will need to convert your percentage (60) by dividing it by 100.
So our final formula is:
60
--- * 10
100
or using your variables:
percentage
---------- * value1
100
I hope I've added to your understanding even if my formula is similar to the previous answers. I wanted to make sure you understood how the formula was derived.
Good luck!
var result = (percentage/100) * value1;
textbox1.Text = result.ToString();
You mean like this?
textbox1.text = (value1 * percentage/100).ToString();
By the way, toString is written ToString in C# with a capital T.
var answer = value1 * (percentage/100);
Wouldn't this just be
percentage/100m*value
?
To get the percentage amount
decimal Value = 1200;
int percentage = 20; //20%
var result=(percentage/100)*(Value);
I would separate the concerns:
Calculate a portion of your original decimal:
decimal result = (value * percentage) / 100.0;
Provide an appropriate formatter to output the result as a percentage:
text = result.ToString("0.0%");
http://www.dotnetperls.com/percentage
You need to divide by 100.
60% = 60/100.
from question it self answer is clear
60% means 60/100 then calculate it with the value
60 / 100 * 10 = 6 use the logic for variables
textbox1.Text = ((percentage /100) * value).ToString();
or
textbox1.Text = ((percentage * .01 ) * value).ToString();