I started doing c# and now I'm having some issues. This is an assignment for the class I am taking. First I created a program that worked, but then I realised I missed out on the whole method thing. So I'm trying to redo the stuff. So basically I'm doing a program that converts fahrenheit to celsius, based on what the user types. So far I have this:
static double FahrenheittoCelsius(double fahr, double cel)
{
fahr = (cel * 9) / 5 + 32;
return fahr;
}
static void Main(string[] args)
{
double cel = 0;
double fahr = 97;
double max_temp = 170.6;
double min_temp = 163.4;
Console.WriteLine("Welcome to the sauna! We will find the optimal temperature for you! ");
do
{
Console.Write("Please type in Fahrenheit: ");
try
{
fahr = double.Parse(Console.ReadLine());
}
catch
{
Console.Write("Only numbers please!");
continue;
}
if (fahr >= max_temp)
{
Console.Write("The temperature you typed is {0} Celsius, type a lower temperature!", Math.Round(cel, 1));
}
else if (fahr <= min_temp)
{
Console.Write("Temperature you typed is {0} Celsius, type a higher temperature!", Math.Round(cel, 1));
}
else if (fahr > min_temp && fahr < max_temp)
{
Console.Write("Now the temperature is {0} celsius and now the temperature is optimal!", Math.Round(cel, 1));
}
} while (fahr > min_temp != fahr < max_temp);
Console.ReadLine();
So excuse my halfass translate since it was all in Swedish.
But my problem is I can't get the equation "fahr = (cel * 9) / 5 + 32 return fahr;" to my try and catch, which worked in my other program (where I didn't use the method). I can't get it to work.
All help is appreciated
Welcome to programming! You have several small issues with your code:
First looking at your method:
static double FahrenheittoCelsius(double fahr, double cel)
{
fahr = (cel * 9) / 5 + 32;
return fahr;
}
The method name should be FahrenheitToCelsius -- each word starting
with a capital letter.
According to the title of the method you are converting fahrenheit to
celsius. based on that you would only need to pass a fehrenheit and
return a celsius. You are passing both but then returning
fehrenheit!?
The formula you have is also wrong. It should be (F − 32) × 5/9 so code-wise:
var cel = (fahr - 32) * 5 / 9;
return cel;
Then in your main you need to call this method
cel = FahrenheitToCelsius(fahr);
static void Main(string[] args)
{
double cel = 0;
double fahr = 97;
double max_temp = 170.6;
double min_temp = 163.4;
Console.WriteLine("Welcome to the sauna! We will find the optimal temperature for you! ");
do
{
Console.Write("Please type in Fahrenheit: ");
try
{
fahr = double.Parse(Console.ReadLine());
cel = FahrenheitToCelsius(fahr);
}
catch
{
Console.Write("Only numbers please!");
continue;
}
Related
Trying to write a simple set of code that converts from fahrenheit into celsius, and there are three set conditions that determines what happens. Either it's too cold, just right or too hot. For some reason no matter the input, it will only reply and say it is too cold. I can't really figure out why.
Here's the code so far;
{
class Program
{
static int FahrenheitToCelsius(int fahrenheit)
{
int celsius = ((fahrenheit - 32) * 5 / 9);
return celsius;
}
static void Main(string[] args)
{
Console.WriteLine("Please enter the desired temperature: ");
int fahrenheit = Convert.ToInt32(Console.ReadLine());
int celsius = FahrenheitToCelsius(fahrenheit);
while (celsius != 75)
if (celsius < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.");
Console.ReadLine();
}
else if (celsius > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.");
Console.ReadLine();
}
else if (celsius == 75)
{
Console.WriteLine("Optimal input! Begin heating up.");
break;
}
else
{
Console.WriteLine("Invalid input! Please input a temperature.");
}
}
}
}
maybe You only getting same message because you haven't change value of celsius
static int FahrenheitToCelsius(int fahrenheit)
{
int celsius = ((fahrenheit - 32) * 5 / 9);
return celsius;
}
static void Main(string[] args)
{
Console.WriteLine("Please enter the desired temperature: ");
int fahrenheit = Convert.ToInt32(Console.ReadLine());
int celsius = FahrenheitToCelsius(fahrenheit);
Console.WriteLine("C = " + celsius);
int i = 0;
while (celsius != 75) {
if (i>0)
{
int x = Convert.ToInt32(Console.ReadLine());
celsius = FahrenheitToCelsius(x);
}
if (celsius < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.");
}
else if (celsius > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.");
}
else if (celsius == 75)
{
Console.WriteLine("Optimal input! Begin heating up.");
break;
}
else
{
Console.WriteLine("Invalid input! Please input a temperature.");
}
i++;
}
}
}
First, Fix your conversion. When converting from one unit to an other one should not remove the decimal value.
static double FahrenheitToCelsius(double f) => (f - 32) * 5.0 / 9.0;
Now lets talk about your if/else. In your code
T <= 163 is too cold;
T = 164,165,166,169,170 are all invalid Temperature;
T >= 171 is too hot;
There is not reason to have those invalid right in the middle of the range.
And there is no explanation on Invalid temp so just drop it.
Is there a number that can satisfy multiple of those condition?
x < 73, x > 77, x ==75...
We can safely drop all the else.
if (tempC < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.\n");
}
if (tempC > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.\n");
}
if (tempC == 75)
{
Console.WriteLine("Optimal input! Begin heating up.\n");
}
Using a Do/While loop we have :
static void Main(string[] args)
{
double tempC , tempF;
do
{
Console.WriteLine("Please enter the desired temperature: ");
tempF = Convert.ToDouble(Console.ReadLine());
tempC = FahrenheitToCelsius(tempF);
Console.WriteLine($"{tempF,4:F}°F, {tempC,4:F}°C");
if (tempC < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.\n");
}
if (tempC > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.\n");
}
if (tempC == 75)
{
Console.WriteLine("Optimal input! Begin heating up.\n");
}
}
while (tempC != 75);
}
Nb renamed the variable from Fahrenheit and Celsius to tempF and tempC.
Temperatur unit find is the while are : C, F, K, R, De, N, Re, Ro.
I'm not sure one can write the name of those without google.
I am new to programming and I think I have confused myself I'm trying to make a loop that asks users for integers when the user inputs a integer greater than 100 then the console displays the amount of integers the user has input and the sum of these integers. I know it's basic but I can't figure where I went wrong.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum1, strNum2;
int num1, num2;
int i = 0;
int sum =0 ;
Console.WriteLine("Please enter a integer between 1 and 100"); // asks for user input
strNum1 = Console.ReadLine();
num1 = int.Parse(strNum1);
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum2 = Console.ReadLine();
num2 = int.Parse(strNum2); //input is stored as num2
sum = num2; //store num2 in sum
i++;
if (num2 >= 100) // if num2 int is greater than 100
{
sum = (num1 +num2 +sum); // do calculation
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
while (i < 100);
}
}
}
any help would be appreciated thanks everyone!
You're on the right track... a couple of things:
Do... While is used when you always want to run through the block at least once, so your first 'get' from the user can be inside the block. You can code whatever you want to happen after the condition fails right after the block, instead of checking the same condition inside it.
Make sure if you're simply using Parse that you wrap it in a try...catch, because your user could type in anything (not just numbers). Personally I usually use TryParse instead.
Finally, make sure you're comparing to the correct variable. Checking that i < 100 will keep looping until 100 numbers have been entered; you want to compare the user's input instead.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string prompt = "Please enter {0} integer between 1 and 100";
string strNum;
int num = 0;
int i = 0;
int sum =0 ;
do //ask once and repeat while 'while' condition is true
{
string pluralPrompt = i > 0 ? "another" : "an";
prompt = string.Format(prompt,pluralPrompt);
Console.WriteLine(prompt); // asks for user input
strNum = Console.ReadLine();
if (!Int32.TryParse(strNum, out num)) //input is stored as num
{
// warn the user, throw an exception, etc.
}
sum += num; //add num to sum
i++;
}
while (num < 100);
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
}
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum;
int num;
int i = 0;
int sum = 0;
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum = Console.ReadLine();
if (int.TryParse(strNum, out num)) //input is stored as num2
{
if (num < 101)
{
i++;
sum += num;
continue;
}
else
{
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
break;
}
}
}
while (i < 100);
}
}
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MortgageApplication
{
class Program
{
static void Main(string[] args)
{
string input = "", year, principle, month;
double r, y, p;
bool valid = false;
y = 0;
r = 0;
p = 0;
while (valid == false)
{
Console.WriteLine("Enter the duration of the loan (Number of Years): ");
input = Console.ReadLine();
if (double.TryParse(input, out y))
{
Console.WriteLine(y);
valid = true;
}
}
valid = false;
while (valid == false)
{
Console.WriteLine("Enter the princple ammount: ");
input = Console.ReadLine();
if (double.TryParse(input, out p))
{
Console.WriteLine(p);
valid = true;
}
}
valid = false;
while (valid == false)
{
Console.WriteLine("Enter the Interest Rate ");
input = Console.ReadLine();
if (double.TryParse(input, out r))
{
valid = true;
}
}
r = r / 100;
Console.WriteLine(r);
double top = p * r / 1200;
Console.WriteLine(top);
double x = (1 + (r / 1200.0));
Console.WriteLine(x);
double n = -12 * y;
Console.WriteLine(n);
double buttom = (1 - (Math.Pow(x, n)) );
Console.WriteLine(buttom);
double solution = top / buttom;
Console.WriteLine(solution);
Console.ReadLine();
}
}
}
This is suppose to be a simple mortgage app. I have the functionality but the formula is not correct.
Not sure if it's because I'm using doubles or if the problem is with my coding.
(p r / 1200.0) / (1 - (1.0 + r / 1200.0) ^(-12.0 n)),
Where
p = principal (dollars)
n = number of years
r = interest rate (percent)
m = monthly payment
So I think the direct answer is that you're dividing the rate by 100, then dividing it again by 1200. You should either not divide by 100 to start with, or only divide by 12 later (I like the second option because it makes it clear you're talking about 12 months).
Another thing you might consider, in order to reduce repeated code, is to factor out a new function that gets a double from the user. Something like:
private static double GetDoubleFromUser(string prompt)
{
double result;
while (true)
{
if (prompt != null) Console.Write(prompt);
var input = Console.ReadLine();
if (double.TryParse(input, out result)) break;
Console.WriteLine("Sorry, that is not a valid number. Please try again...");
}
return result;
}
Now, when you need a double, you just call this function and pass the prompt string. This makes your code much cleaner and easier to read. For example, your code could now be written as:
private static void Main()
{
double years = GetDoubleFromUser("Enter the duration of the loan (in years): ");
double principal = GetDoubleFromUser("Enter the princple ammount: ");
double rate = GetDoubleFromUser("Enter the interest rate: ") / 100;
Console.WriteLine("\nBased on these values entered:");
Console.WriteLine(" - Number of years .... {0}", years);
Console.WriteLine(" - Principal amount ... {0:c}", principal);
Console.WriteLine(" - Interest rate ...... {0:p}", rate);
double monthlyRate = rate / 12;
double payments = 12 * years;
double result =
principal *
(monthlyRate * Math.Pow(1 + monthlyRate, payments)) /
(Math.Pow(1 + monthlyRate, payments) - 1);
Console.WriteLine("\nYour monthly payment will be: {0:c}", result);
Console.ReadLine();
}
Hi it is just a simple calculator. I want to allow user to enter "N" or "n" after I asked them if they want to make an another conversion.
(Enter Y to make an another conversion/Enter N return to Main menu). How do I do that?
static int LengthCalculator() {
int LengthCalculatorOption;
string AnotherConversion = null;
double Centimetres = 0.0, Feet = 0.0, Inches = 0.0, TotalInches = 0.0;
const double CENTIMETRES_PER_INCH = 2.54, INCHES_PER_FOOT = 12;
do {
LengthCalculatorMenu();
LengthCalculatorOption = ValidLengthCalculatorReadOption();
if (LengthCalculatorOption == 1) {
Console.WriteLine("Please Enter the Centimetres(cm) that you wish to convert to feet and inches:");
Centimetres = double.Parse(Console.ReadLine());
TotalInches = (Centimetres / CENTIMETRES_PER_INCH); // This will take a floor function of Centimetres/2.54
Feet = (TotalInches - TotalInches % INCHES_PER_FOOT) / INCHES_PER_FOOT; // This will make it divisible by 12
Inches = TotalInches % INCHES_PER_FOOT; // This will give you the remainder after you divide by 12
Console.WriteLine("\nThe equivalent in feet and inches is {0} ft {1} ins", Feet, Inches);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any key return to Main menu):");
AnotherConversion = Console.ReadLine();
} else if (LengthCalculatorOption == 2) {
Console.WriteLine("Please Enter the Feet:");
Feet = double.Parse(Console.ReadLine());
Console.WriteLine("Please Enter the Inches:");
Inches = double.Parse(Console.ReadLine());
Centimetres = ((Feet * INCHES_PER_FOOT) + Inches) * CENTIMETRES_PER_INCH;
Console.WriteLine("\nThe equivalent in centimetres is {0}cm", Centimetres);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any key return to Main menu):");
AnotherConversion = Console.ReadLine();
}
} while (AnotherConversion == "y" || AnotherConversion == "Y");
return LengthCalculatorOption;
}//End LenthCalculator
static void LengthCalculatorMenu() {
string LengthCalculatorMenu = ("Enter 1) Convert Centimetres to Feet and Inches:"
+ "\nEnter 2) Convert feet and inches to centimetres:");
Console.WriteLine(LengthCalculatorMenu);
} // End LengthCalculatorMenu
static int ValidLengthCalculatorReadOption() {
int LengthCalculatorOption;
bool ValidLengthCalculatorOption = false;
do {
LengthCalculatorOption = int.Parse(Console.ReadLine());
if ((LengthCalculatorOption >= 1) && (LengthCalculatorOption <= 2)) {
ValidLengthCalculatorOption = true;
} else {
ValidLengthCalculatorOption = false;
} // end if
if (!ValidLengthCalculatorOption) {
Console.WriteLine("\n\t Option must be 1 or 2, Please Re-Enter your Option");
LengthCalculatorMenu();
} //end if
} while (!ValidLengthCalculatorOption);
return LengthCalculatorOption;
}// End LengthCalculatorReadOption
static int ReadMainMenuOption() {
int option = 0;
bool ValidMainMenuOption = false;
do {
option = int.Parse(Console.ReadLine());
if ((option >= 1) && (option <= 5)) {
ValidMainMenuOption = true;
} else {
ValidMainMenuOption = false;
} // end if
if (option == 1) {
LengthCalculator();
} else if (option == 2) {
} else if (option == 3) {
} else if (option == 4) {
} else if (option == 5) {
} // end if
if (!ValidMainMenuOption) {
Console.WriteLine("\n\t\a Option must be 1,2,3,4 or 5");
DisplayMenu();
} //end if
} while (!ValidMainMenuOption);
return option;
} //end ReadOption
/* Displays Main Menu
* Precondition:true
* postcondition: DisplayMenu displayed
*/
static void DisplayMenu() {
string mainMenu = "\n1)Length Calculator"
+ "\n2)Body Mass Index Calculator"
+ "\n3)Waist to Height Calculator"
+ "\n4)Fuel Consumption Calculator"
+ "\n5)Exit the Calculator"
+ "\n\nEnter your option(1,2,3,4 or 5 to exit):";
Console.Write(mainMenu);
} //end DisplayMenu
static void Main(string[] args) {
const int Exit = 5;
int menuOption;
do {
DisplayMenu();
menuOption = ReadMainMenuOption();
} while (menuOption != Exit);
Console.Write("Thank you for using this Calculator. Press any Key to Exit");
//terminating message
Console.ReadKey();
}//end Main
You can make a separate method that will handle user input. For example, this method will determine if the user has entered a Y or N. If they haven't it re-prompt them to do so:
static bool AnotherConversion()
{
var prompt = "\nWould you like to make an another conversion? \n\n(Enter (Y) to make another conversion or (N) to return to the Main Menu):";
Console.WriteLine(prompt);
while (true)
{
var userInput = Console.ReadLine();
if (String.Compare("Y", userInput, StringComparison.Ordinal)
{
return true;
}
else if (String.Compare("N", userInput, StringComparison.Ordinal)
{
return false;
}
else
{
// Invlalid input, re-prompt
Console.WriteLine("Invalid Input, please enter or (Y) or (N)!");
Console.WriteLine(prompt);
}
}
}
You can them simply update your do/while loop so that the condition is based on the AnotherConversion method. This will allow the prompt to be asked whenever a calculation is done:
static int LengthCalculator() {
....
do {
.....
} while (AnotherConversion());
return LengthCalculatorOption;
}//End LenthCalculator
Call to this method in the place you want:
static bool shouldMakeAnotherConversion()
{
repeatQuestion:
// This shows the question to the user
Console.Write("Do you want to make another conversion (Y/N)? ");
ConsoleKeyInfo answer = Console.ReadKey(true);
switch (answer.Key)
{
case ConsoleKey.Y: return true;
case ConsoleKey.N: return false;
}
//If the user types any other key, the program will repeat the question
Console.WriteLine();
goto repeatQuestion;
}
class Program
{
public static void parameter(int num1, int num2, out int add, out int sub, out int mul, out float div)
{
add = num1 + num2;
sub = num1 - num2;
mul = num1 * num2;
div = (float)num1 / num2;
}
static void Main(string[] args)
{
int num1, num2;
int add, sub, mul;
float div;
Console.Write("Enter 1st number\t");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nEnter 2nd number\t");
num2 = Convert.ToInt32(Console.ReadLine());
Program.parameter(num1, num2, out add, out sub, out mul, out div);
Console.WriteLine("\n\n{0} + {1} = {2}", num1, num2, add);
Console.WriteLine("{0} - {1} = {2}", num1, num2, sub);
Console.WriteLine("{0} * {1} = {2}", num1, num2, mul);
Console.WriteLine("{0} / {1} = {2}", num1, num2, div);
Console.ReadLine();
}
}
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type you first number :");
Console.WriteLine("Type you second number :");
Console.WriteLine("Enter the operation + (addition), - (soustraction), * (multiplication), / (division)");
string stringOperation = Console.ReadLine();
switch (operation)
{
case 1:
result = firstNumber + secondNumber;
break;
case 2:
result = firstNumber - secondNumber;
break;
case 3:
result = firstNumber * secondNumber;
break;
case 4:
result = firstNumber / secondNumber;
break;
}
}
}
}
In C# how do i ask user for starting and stopping point within the array?
Below is my code so far:
class Program
{
static void Main(string[] args)
{
double[] num = { 10, 20, 30, 40, 50 };
double n = num.Length;
Console.Write("Elements of, arrary are:" + Environment.NewLine);
for (int i = 0; i < n; i++)
{
Console.WriteLine(num[i]);
}
double sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + num[i];
}
Console.WriteLine("The sum of elements:" + sum);
Console.ReadKey();
}
}
You'll take the sum of the elements between starting and stopping point, as I guess. Take two inputs from the user and assign them to starting and ending points to the for-loop. Such as:
int startingPoint = Convert.ToInt32(Console.ReadLine());
int endingPoint = Convert.ToInt32(Console.ReadLine());
for(int i = startingPoint; i <= endingPoint; i++)
{
//take sum etc.
}
Don't forget to inform the user about the element values in the array and what input value they are entering at that moment.
Another important thing here is to control the inputs. They should be numeric and between 0-n, starting point should be smaller than ending point.
For numeric control you can write like follows:
if (int.TryParse(n, out startingPoint))
{
// operate here
}
else
{
Console.WriteLine("That's why I don't trust you, enter a numeric value please.");
}
startingPoint should be between 0-n and cannot be n. To control it:
if (startingPoint >= 0 && startingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between 0 and " + n + ".");
}
After taking startingPoint successfully, you should control if endingPoint. It should be between startingPoint-n. After controlling for being numeric you can write as follows:
if (endingPoint >= startingPoint && endingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between " + startingPoint + " and " + n + ".");
}
I don't know what can I explain more for this question. Please let me know for further problems.
If you want to prompt the user for the start and end indexes:
Console.WriteLine("Please enter start index");
string startIndexAsString = Console.ReadLine();
int startIndex = int.Parse(startIndexAsString);
Console.WriteLine("Please enter end index");
string endIndexAsString = Console.ReadLine();
int endIndex = int.Parse(endIndexAsString);
var sum = num.Skip(startIndex).Take(endIndex - startIndex + 1).Sum();