I'm wondering if someone can help me with decimals? Im going to make a program there can wright price and how much you paid, and then get a change back, but i need to add decimals. The decimals have to round up or down, so if it is 0,11 it goes to 0, if it is o,20 it goes to 0,25. So it will round up to either 0,25, 0,50, 0,75 and later on 1. The change have too also show in which cash you get back, so like 100 bucks, 500 bucks, 50 bucks if you know what i mean. I dont know how to do. This is how long i come:
using System;
namespace inlämninguno
{
class Program
{
// Starting point of my "Change" program
static void Main(string[] args)
{
Console.WriteLine(Subtract()); // adding a subract variable in the beginning of the code
Console.Read();
}
// Using the double datatype to for the decimals
public static double Subtract()
{
Console.WriteLine("Price?"); // how much it costs
string number1Input = Console.ReadLine();
Console.WriteLine("Paid?"); // how much the customer pays
string number2Input = Console.ReadLine();
double prince = Convert.ToDouble(number1Input);
double paid = Convert.ToDouble(number2Input);
// This is for the subtracting part
double num1 = double.Parse(number1Input);
double num2 = double.Parse(number2Input);
double result = num2 - num1; // this is so the console subtracts the values, have to put num2 first so the output isn't negative
Console.Write("Your change is " + result + ":"); // Output "Your change is ..."
return result; // A method that gives the right output of the code
}
}
}
Can someone please help me? Im stuck :D
I tried to convert to double and lots of stuff, but I don't know how to do now.
Related
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);
}
}
The program I am creating prompts the user to enter an amount of months, the amount of work absences he/she has had in each month, and the amount of absences allowed per month. It is supposed to calculate the average amount of work absences by an employee as well as the amount of times that he/she went over the max absences allowed.
I was able to calculate the average with an array loop but was having issues with the times he/she has gone over the max absences. I am using the binary search method but have trouble outputting the specific amount of months that the employee has gone over the allowed absence amount.
This is my current code for that section:
for (int i = 0; i < numbOfAbsences.Length; i++)
{
sum += numbOfAbsences[i];
averageAbsences = (sum / numbOfMonths);
Console.WriteLine("Employee was absent " + averageAbsences + " times per month.");
}
a = Array.BinarySearch(numbOfAbsences, maxAbsences);
if (a >= maxAbsences)
{
}
I am unsure of what would go under the last set of brackets, as I am not trying to point out whether the max amount was exceeded but rather the amount of times that it was.
Thank you for the help in advanced.
First off, the question is not clearly stated. It boils down to this:
"What's a good way to take an int array of sums and divide them all by a count to produce a double array of averages? Also, how can I count the values of an int array greater than a threshold? (Here's what I've got so far: )"
Second, the code snippet is very confusing. More precisely... It's not indented correctly. Not all of the variables used are defined, so we have to guess what they are. The variable names aren't very descriptive, so one has to look at how each variable is used to understand it. Most importantly however, this is no encapsulation. No objects, no functions... just raw code that you need to read every line of very carefully to understand.
Contrast the snippet with this:
using System;
using System.Linq;
namespace ArraySearch_StackOverflow
{
class Program
{
static void Main(string[] args)
{
int[] employeeAbsencesEachMonth = new int[] { 1, 2, 3, 4, 5, 6 };
int maxAbsencesAllowedPerMonth = 3;
double averageAbsencesPerMonth = GetAverageAbsencesPerMonth(employeeAbsencesEachMonth);
Console.WriteLine($"Employee's Average Absences Per Month: {averageAbsencesPerMonth}"); /* 3 */
int numTimesMaxAbsencesExceeded = GetNumMaxAbsencesViolations(employeeAbsencesEachMonth, maxAbsencesAllowedPerMonth);
Console.WriteLine($"Number of Times Employee Exceeded Max Absence Limit: {numTimesMaxAbsencesExceeded}"); /* 3 */
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
private static double GetAverageAbsencesPerMonth(int[] employeeAbsencesEachMonth)
{
// ???
throw new NotImplementedException();
}
private static int GetNumMaxAbsencesViolations(int[] employeeAbsencesEachMonth, int maxAbsencesAllowedPerMonth)
{
// ???
throw new NotImplementedException();
}
}
}
This snippet is extremely clear. Even without a description, it's immediately apparent what's being asked, and how to tell if an answer is correct. Because the questions have been translated into a function signature and the context has been translated into a driver in which the functions are called, complete with setup and an expected result.
Handily, this implies a simple format for the answer, creating a good chance you can copy-paste it directly into your code:
private static double GetAverageAbsencesPerMonth(int[] employeeAbsencesEachMonth)
{
return employeeAbsencesEachMonth.Sum() / employeeAbsencesEachMonth.Length;
}
private static int GetNumMaxAbsencesViolations(int[] employeeAbsencesEachMonth, int maxAbsencesAllowedPerMonth)
{
return employeeAbsencesEachMonth.Count(x => x > maxAbsencesAllowedPerMonth);
}
Okay, so here is what I have, the console runs and accepts any number for the first input and outputs all the outputs but it skips the rest of the reads after the first one. I am new to C# and want to learn so I definetly feel like I am just missing something stupid here. Do not worry about the purpose as I only want help with this problem I am facing now.
Thanks guys,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stamps
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, and welcome to the U.S. Mail Stamp Printer. Now, to print the correct stamp for your postage, please enter the number of half ounces (so 1= .5 ounce, 2 = 1 ounce) your package will weigh \n");
double i = Console.Read();
Console.WriteLine("Thank you, now, will you be sending to zone 1, 2, or 3? Simply enter the zone number and press enter\n");
double z = Console.Read();
Console.WriteLine("Great! Now, last question before I print your stamp, will you be using Local Mail or Air Mail, use the number 1 for local and the number 2 for air.\n");
double m = Console.Read();
if (m == 2)
{
double m2 = .95;
}
else
{
double m2 = .49;
}
if( i == 1)
{
double i2 = 1;
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
The Console.Read method doesn't parse input, it only reads one character from the input stream.
Use the Console.ReadLine method and parse the string that you get:
double i = Double.Parse(Console.ReadLine());
or:
int z = Int32.Parse(Console.ReadLine());
If you want to handle invalid input you would use the TryParse methods, they will return a boolean that tell you if the parsing worked or not.
Side note: When you try to use the m2 and i2 variables you will notice that it doesn't exist. The variable is local for the code blocks in the if statement, so you need to declare it outside to be able to use it later:
double m2;
if (m == 2)
{
m2 = .95;
}
else
{
m2 = .49;
}
you can flush you console buffer or you can used console.readline().
For more information refer below post which give yours question answer.
http://stackoverflow.com/questions/7302544/flushing-system-console-read
I am trying to increment the value of 0001 to 0002. I've tried integers, but that rounds it off to 2. I have also tried to add floats, with the same effect:
float newInt = float.Parse("0001") + float.Parse("0001");
How would one increment numbers formatted as 0001?
You should keep your values and your formatting separate from one another (a).
Simply maintain an integer variable and, when you want it displayed as width four, left padded with zeros, just use something like:
String sNum = num.ToString("D4");
as per the following complete program:
using System;
namespace test {
class Program {
static void Main(string[] args) {
int x = 8;
x++; Console.WriteLine(x.ToString("D4"));
x++; Console.WriteLine(x.ToString("D4"));
x++; Console.WriteLine(x.ToString("D4"));
Console.ReadLine(); // just because I'm in the IDE.
}
}
}
which outputs:
0009
0010
0011
(a) You can certainly do what you ask, with something like:
using System;
namespace test {
class Program {
static void Main(string[] args) {
String s = "0008";
s = (Int32.Parse(s) + 1).ToString("D4"); Console.WriteLine(s);
s = (Int32.Parse(s) + 1).ToString("D4"); Console.WriteLine(s);
s = (Int32.Parse(s) + 1).ToString("D4"); Console.WriteLine(s);
Console.ReadLine();
}
}
}
But you should be aware that continuously converting a string back to an integer to increment it, then back to a string to display it, is needlessly inefficient. If one of my minions bought me that code for a review, well, I can't tell you the fun I'd have tearing it apart :-)
String sNum = num.ToString("0000");
I have done a homework assignment, here is the problem statement:
Your program should work as follows:
Ask the user to give you a file name. Get the file name and save it.
Open the file.
From the file read a temperature and a wind speed. Both values should be stored in variables declared as double. The file is a text file. Each line of the file contains a temperature and a wind speed value.
Calculate the wind chill factor using a programmer written method, and display the result in the form:
For t = temperature from file
and v = wind speed from file
Wind chill index = calculated result degrees Fahrenheit.
Show all numbers with two digits after the decimal point. (Remember-no magic numbers!)
Repeat these steps until an end of file is encountered.
I have completed the assignment, my code is below, I was just wondering if there was any way to make it more efficient, or if there are some different and creative ways to accomplish this problem, I already turned this in and got 50/50, but I'm just curious as to how some of you advanced and skilled programmers would approach this problem.
using System;
using System.IO;
class Program
{
// declare constants to use in wind chill factor equation - no magic numbers
const double FIRST_EQUATION_NUMBER = 35.74;
const double SECOND_EQUATION_NUMBER = 0.6215;
const double THIRD_EQUATION_NUMBER = 35.75;
const double FOURTH_EQUATION_NUMBER = 0.4275;
const double EQUATION_EXPONENT = 0.16;
const int DEGREE_SYMBOL_NUMBER = 176;
static void Main()
{
// declare and initialize some variables
string filePath = "";
string line = "";
double temperature = 0.0;
double windSpeed = 0.0;
double windChillFactor = 0.0;
char degreeSymbol = (char)DEGREE_SYMBOL_NUMBER;
// ask user for a file path
Console.Write("Please enter a valid file path: ");
filePath = Console.ReadLine();
// create a new instance of the StreamReader class
StreamReader windChillDoc = new StreamReader(#filePath);
// start the read loop
do
{
// read in a line and save it as a string variable
line = windChillDoc.ReadLine();
// is resulting string empty? If not, continue execution
if (line != null)
{
string[] values = line.Split();
temperature = double.Parse(values[0]);
windSpeed = double.Parse(values[1]);
windChillFactor = WindChillCalc(temperature, windSpeed);
Console.WriteLine("\nFor a temperature {0:f2} F{1}", temperature, degreeSymbol);
Console.WriteLine("and a wind velocity {0:f2}mph", windSpeed);
Console.WriteLine("The wind chill factor = {0:f2}{1}\n", windChillFactor, degreeSymbol);
}
} while (line != null);
windChillDoc.Close();
Console.WriteLine("\nReached the end of the file, press enter to exit this program");
Console.ReadLine();
}//End Main()
/// <summary>
/// The WindChillCalc Method
/// Evaluates a wind chill factor at a given temperature and windspeed
/// </summary>
/// <param name="temperature">A given temperature</param>
/// <param name="ws">A given windspeed</param>
/// <returns>The calculated wind chill factor, as a double</returns>
static double WindChillCalc(double temperature, double ws)
{
double wci = 0.0;
wci = FIRST_EQUATION_NUMBER + (SECOND_EQUATION_NUMBER * temperature) - (THIRD_EQUATION_NUMBER * (Math.Pow(ws, EQUATION_EXPONENT))) + (FOURTH_EQUATION_NUMBER * temperature * (Math.Pow(ws, EQUATION_EXPONENT)));
return wci;
}
}//End class Program
Feel free to tell me what you think of it.
Your way looks good, but:
It would look nicer if you used PascalCase for the constants, as that's what coding conventions for c# use.
you should wrap the StreamReader in a using statement, so it gets properly disposed once you're done.
You should probably also wrap it in a try block (and a catch to properly handle the exception) to make sure that you don't get a FileNotFound exception.
It's probably a better idea to structure your while loop the following way:
while((line = windChillDoc.ReadLine()) != null)
{
...
}
[Darn formatting won't work right!]
Other than that though, i wouldn't know as i'm not familiar with weather calculations :)
You're not going to get much zippier than that for file IO in C#. Depending on the size of the data set it may be worth using a buffered reader, but for sufficiently small files, it's just not worth it. I'd leave it as-is.
Most of your comments are extraneous. The code should tell you how...the comments should tell you why.
Minor nitpick, but "WindChillCalc" should be "CalcWindChill" if you are are using English method names (the verb goes first).
string filePath = "";
...
filePath = Console.ReadLine();
Don't initialize with values that are never used; and keep declaration and initialization close together:
string filePath = Console.ReadLine();
using has been mentioned - but don't use # unnecessarily:
new StreamReader(#filePath);
should be just:
new StreamReader(filePath);
Personally, I'd use LINQ for the line-reader, but that is just me ;-p
Why the do/while? In your do you check for null. In your while you check for null. Why not just make it a while statement?
string line;
while((line = windChillDoc.ReadLine()) != null)
{
//Logic
}
EDIT: Fixed the compilation error. Funny thing was I had that originally. This Rich Text Box needs a compiler! :P
Although not really relating to performance (the main question)
IMO:
const double FIRST_EQUATION_NUMBER = 35.74;
const double SECOND_EQUATION_NUMBER = 0.6215;
const double THIRD_EQUATION_NUMBER = 35.75;
const double FOURTH_EQUATION_NUMBER = 0.4275;
const double EQUATION_EXPONENT = 0.16;
isn't much better than a magic number. Looking at that I have no idea what FIRST_EQUATION_NUMBER is used for other than in an equation somewhere, and I can't tell that they are in the same equation or you have four equations which use different numbers? They could also be put into the actual method as thats the only place they are used.
I would change degreeSymbol to a const rather than working it from a const int
later.
const char DEGREE_SYMBOL = (char)176;
If you're getting marked on style etc. then there's a couple extremely minor things
Initializing doubles to 0.0 is redundant.
string.Empty is preferred instead of ""
Your windchill method can be changed to simply (though, during compilation, I think that wci will be optimized out - so it's functionally the same):
(changed formatting for SO readability)
static double WindChillCalc(double temperature, double ws)
{
return FIRST_EQUATION_NUMBER +
(SECOND_EQUATION_NUMBER * temperature) -
(THIRD_EQUATION_NUMBER * (Math.Pow(ws, EQUATION_EXPONENT))) +
(FOURTH_EQUATION_NUMBER * temperature * (Math.Pow(ws, EQUATION_EXPONENT)));
}
In little academic programs like this, unless you do something really dumb, performance will not be an issue. A simple way to tell if performance is an issue is to ask the question: "Does it make me wait?"
If there were an enormous amount of input, I would ask who's providing the input and who's reading the output. That would tell me if I could do the I/O in binary rather than text, because as it is, by far the bulk of the processing will be in the conversion of text into numbers on input, and numbers to text on output, especially floating point.