Why do I need a double? [duplicate] - c#

This question already has answers here:
C# short/long/int literal format?
(5 answers)
Closed 2 years ago.
Simply put, I'm very new and I do not understand why I need total to be a double, my teacher put it as a float in his program, but it doesn't work for me.
int choix;
double total = 0;
do
{
Console.WriteLine("Menu\n\n");
Console.WriteLine("1 - Pizza 3.25$\n");
Console.WriteLine("2 - Poutine 2.75$\n");
Console.WriteLine("3 - Liqueur 1.25$\n");
Console.WriteLine("4 - Fin\n\n");
Console.WriteLine("Votre choix(1 - 4)");
choix = int.Parse(Console.ReadLine());
switch(choix)
{
case 1:total = total + 3.25;
break;
case 2:total = total + 2.75;
break;
case 3:total = total + 1.25;
break;
case 4:Console.WriteLine("Voici le total " + total);
break;
default:Console.WriteLine("Erreur de choix");
break;
}
}
while (choix != 4);
Sorry for this dumb question, but I cannot find answers anywhere.

Basically because of how c# interprets the code, c# doesnt know whether your decimal numbers will overflow or not, so it automatically assign all floating values as a double (which can actually hold more values than a float). So what you need to do in order to the compiler understand that you actually want a float, is to add an f at the end of the numbers.
int choix;
float total = 0;
do
{
Console.WriteLine("Menu\n\n");
Console.WriteLine("1 - Pizza 3.25$\n");
Console.WriteLine("2 - Poutine 2.75$\n");
Console.WriteLine("3 - Liqueur 1.25$\n");
Console.WriteLine("4 - Fin\n\n");
Console.WriteLine("Votre choix(1 - 4)");
choix = int.Parse(Console.ReadLine());
switch (choix)
{
case 1:
total = total + 3.25f;
break;
case 2:
total = total + 2.75f;
break;
case 3:
total = total + 1.25f;
break;
case 4:
Console.WriteLine("Voici le total " + total);
break;
default:
Console.WriteLine("Erreur de choix");
break;
}
}
while (choix != 4);

Related

Number guessing game c#. Tie least guesses to best round and vice versa

I'am super new to coding and this is probably an easy fix but I just dont know how to solve it or what exactly to search for. I'm doing this assignment from school and it's a random number guessing game. In this assignment they want to know which round was the best round.
The problem I have is that I want to implement a sort of a round tracker and simultaneously tie the best/worst amount of guesses to the best/worst round the user guessed.
I hope I'am being clear with what I'm asking, I don't know the coding language too well.
This is what I've done so far and I just can't tie the "int min_tries/max_tries" to a specific round number.
else
{
BestRound.Add(tries);
RoundNumber.Add(rounds);
totaltries++;
tries++;
Console.WriteLine();
Console.WriteLine(guess + " is correct. You win! It took you " + tries + " tries to guess right!");
Console.WriteLine();
Console.WriteLine("Do you want to play again? Yes/No?");
playAgain = Console.ReadLine();
if (playAgain.Equals("Yes", StringComparison.OrdinalIgnoreCase))
{
reset = true;
}
else
{
reset = false;
}
}
if (attempt >= totalattemtp)
{
BestRound.Add(tries);
RoundNumber.Add(rounds);
Console.WriteLine("!GAME OVER!");
Console.WriteLine("You have have no attempts left.");
Console.WriteLine();
Console.WriteLine("Do you want to play again? Yes/No?");
playAgain = Console.ReadLine();
if (playAgain.Equals("Yes", StringComparison.OrdinalIgnoreCase))
{
reset = true;
}
else
{
reset = false;
}
break;
}
}
}
int max_tries = BestRound.AsQueryable().Max();
int min_tries = BestRound.AsQueryable().Min();
int best_round = RoundNumber.AsQueryable().Min();
int worst_round = RoundNumber.AsQueryable().Max();
if(BestRound.AsQueryable().Max() == 10)
{
max_tries = 10 - 1;
Console.WriteLine("Thank you for playing! Your total tries where " + totaltries + ".");
Console.WriteLine("Your best round was number " + best_round + " and had " + (min_tries + 1) + " tries.");
Console.WriteLine("Your worst round was round number " + worst_round + " and had " + (max_tries + 1) + " tries.");
}
else
{
//thanking user for playing and keeping program running until random key-input.
Console.WriteLine("Thank you for playing! Your total tries where " + totaltries + ".");
Console.WriteLine("Your best round was number " + best_round + " and had " + (min_tries + 1) + " tries.");
Console.WriteLine("Your worst round was round number " + worst_round + " and had " + (max_tries + 1) + " tries.");
}
Console.WriteLine("Press enter to quit.");
Console.ReadKey();
This is what I was talking about in the comments.
Create a simple POCO ("Plain old CLR object") class named RoundInfo to hold the results of a round:
internal class RoundInfo
{
public int RoundNumber { get; set; }
public int NumTries { get; set; }
public int NumberToGuess { get; set; }
public RoundInfo(int roundNumber, int numTries, int numberToGuess)
{
RoundNumber = roundNumber;
NumTries = numTries;
NumberToGuess = numberToGuess;
}
}
It's just three properties and a convenience constructor.
Now to plug it into a guessing game... Here's a guessing game I threw together:
var random = new Random();
var round = 1;
var timeToQuit = false;
Console.WriteLine("Welcome to the Guessing Game");
var roundsInformation = new List<RoundInfo>();
while (!timeToQuit) {
var numToGuess = random.Next(10) + 1;
var guess = -1;
var tries = 1;
Console.WriteLine($"Round {round}:");
while (true)
{
guess = GetNumberFromUser("Enter a guess between 1 and 10", 1, 10);
if (guess == numToGuess)
{
Console.WriteLine($"Congratulation, you guessed correctly in {tries} tries");
// Here is where I add the result from this round into the list of round information
roundsInformation.Add(new RoundInfo(round, tries, numToGuess));
Console.Write("Is it time to Quit (Y/N): ");
var response = Console.ReadLine();
if (response.Equals("Y", StringComparison.CurrentCultureIgnoreCase) || response.Equals("Yes", StringComparison.CurrentCultureIgnoreCase))
{
timeToQuit = true;
}
break; //from the inner "while(true)"
}
++tries;
}
++round;
}
Then, once the user has quit, I simply sort the list of round information (using LINQ's orderby) to show him/her the results:
var sortedResults = (from result in roundsInformation orderby result.NumTries select result).ToList();
Console.WriteLine("Here are your results (Best to worst):");
foreach (var result in sortedResults)
{
Console.WriteLine($"Round {result.RoundNumber}, trying to guess: {result.NumberToGuess}, {result.NumTries} tries");
}
Console.ReadLine();
Note that I call GetNumberFromUser to get the number from the user. I like to do my UI checking outside the main logic of the program. Here is that method:
static int GetNumberFromUser(string prompt, int min, int max)
{
while (true) {
Console.Write($"{prompt}: ");
var read = Console.ReadLine();
if (int.TryParse(read, out var number) && number >= min && number <= max){
return number;
}
Console.WriteLine($"Entered data must be an integer between {min} and {max} inclusive");
}
}
If I run this program, I get something like this in the console:
Welcome to the Guessing Game
Round 1:
Enter a guess between 1 and 10: 1
Enter a guess between 1 and 10: 0
Entered data must be an integer between 1 and 10 inclusive
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 11
Entered data must be an integer between 1 and 10 inclusive
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 4
Enter a guess between 1 and 10: abc
Entered data must be an integer between 1 and 10 inclusive
Enter a guess between 1 and 10: 5
Enter a guess between 1 and 10: 6
Congratulation, you guessed correctly in 6 tries
Is it time to Quit (Y/N): n
Round 2:
Enter a guess between 1 and 10: 1
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 4
Enter a guess between 1 and 10: 5
Enter a guess between 1 and 10: 6
Enter a guess between 1 and 10: 7
Enter a guess between 1 and 10: 8
Enter a guess between 1 and 10: 9
Enter a guess between 1 and 10: 10
Congratulation, you guessed correctly in 10 tries
Is it time to Quit (Y/N): n
Round 3:
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 5
Congratulation, you guessed correctly in 3 tries
Is it time to Quit (Y/N): n
Round 4:
Enter a guess between 1 and 10: 1
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 4
Congratulation, you guessed correctly in 4 tries
Is it time to Quit (Y/N): y
Here are your results (Best to worst):
Round 3, trying to guess: 5, 3 tries
Round 4, trying to guess: 4, 4 tries
Round 1, trying to guess: 6, 6 tries
Round 2, trying to guess: 10, 10 tries

Need help Improving Basic C# Calculator [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I made this Basic C# Calculator to reflect on what I've learned these past few days. I'm an absolute beginner and I wanted to get suggestions on improving and shortening it.
I've tried to add switch statements and multiple methods, but it has been really hard grasping them.
using System;
namespace lol
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hi! What is your name?");
string name = Console.ReadLine();
Console.WriteLine(name + " What do you wanna do?");
Console.WriteLine("Type \"+\" for addition");
Console.WriteLine("Type \"-\" for Subraction");
Console.WriteLine("Type \"*\" for Multiplication");
Console.WriteLine("Type \"/\" for division");
string operation = Console.ReadLine();
Console.Write("Now, Give me number one: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Now give me number two: ");
double num2 = Convert.ToDouble(Console.ReadLine());
if (operation == "+")
{
Console.WriteLine(num1 + num2);
}
else if (operation == "-")
{
Console.WriteLine(num1 - num2);
}
else if (operation == "*")
{
Console.WriteLine(num1 * num2);
}
else
{
Console.WriteLine(num1 / num2);
}
}
}
}
If it better for your eyes, you can write like that:
static class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hi! What is your name?");
string name = Console.ReadLine();
Console.WriteLine(name + " What do you wanna do?");
string[] operations = new string[] { "\"+\" for addition", "\"-\" for subtraction", "\"*\" for multiplication", "\"/\" for divsion" };
foreach (string operation in operations) { Console.WriteLine("Type " + operation); }
string cmd = Console.ReadLine();
Console.Write("Now, Give me number one: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Now give me number two: ");
double num2 = Convert.ToDouble(Console.ReadLine());
switch (cmd)
{
case "+": Console.WriteLine(num1 + num2); break;
case "-": Console.WriteLine(num1 - num2); break;
case "*": Console.WriteLine(num1 * num2); break;
case "/": Console.WriteLine(num1 / num2); break;
}
}
}
Using enums and checking if the user input is valid. I also added a loop that checks if the user wants to input equations.
References:
double.TryParse
Enum
Switch Case
You can try it here: https://dotnetfiddle.net/aIwX5P
using System;
public class Program
{
enum eOperator
{
opAdd = 0,
opSub = 1,
opDiv = 2,
opMul = 3,
opInvalid = int.MinValue + 1,
opQuit = int.MinValue
}
public static void Main()
{
double a = 0.0, b = 0.0;
eOperator op = eOperator.opQuit;
string input = String.Empty;
Console.WriteLine("Calculator");
Console.WriteLine("Enter 'quit' at any time to exit.");
// repeat until the user wants to quit.
do // while(op != eOperator.opQuit)
{
Console.Write("a = ");
input = Console.ReadLine().ToLower().Trim();
if (double.TryParse(input, out a))
{
// input is a valid double and was stored in a
Console.Write("Operator: ");
input = Console.ReadLine().ToLower().Trim();
switch (input)
{
case "+":
op = eOperator.opAdd;
break;
case "-":
op = eOperator.opSub;
break;
case "*":
op = eOperator.opMul;
break;
case "/":
op = eOperator.opDiv;
break;
case "quit":
op = eOperator.opQuit;
break;
default:
op = eOperator.opInvalid; // can't be left as quit
Console.WriteLine("Invalid entry. +, -, *, / or quit for operator.");
break;
}
if (op != eOperator.opQuit && op != eOperator.opInvalid)
{
// user didn't choose to quit or type something invalid
Console.Write("b = ");
input = Console.ReadLine().ToLower().Trim();
if (double.TryParse(input, out b))
{
// input is a valid double and was parsed into b
double result = a; // we use the operator on a, so we might as well just store a into the result right away.
// do the operation on result.
switch (op)
{
case eOperator.opAdd:
result += b;
break;
case eOperator.opSub:
result -= b;
break;
case eOperator.opMul:
result *= b;
break;
case eOperator.opDiv:
// Div by 0 check. without this, this still works since double has +/- inf values.
if (b != 0.0) // comparing double with = and != is usually bad idea, but 0.0 is saved without rounding errors.
{
result /= b;
}
else
{
Console.WriteLine("Div by 0");
op = eOperator.opInvalid;
}
break;
default:
// this if branch checked for the other two operators. since we never chanced op after that check, this exception should never happen.
// it is still a good idea to include it to find errors in your logic, should they have occurred.
throw new Exception("This shouldn't happen.");
}
if (op != eOperator.opInvalid)
{
Console.WriteLine("Result: " + result.ToString());
}
// the only invalid operation is div by 0 for now. the message was sent to the user in that case, so no else is needed at this point.
// alternatively you can store an error message into a string, and when op = opInvalid, then display that error message here centralized.
// this would be a good idea if multiple things can go wrong.
}
else if (input == "quit")
{
// input for b was an invalid number, but input was 'quit'
op = eOperator.opQuit;
}
else
{
// input for b was an invalid number and also not 'quit', display error message
Console.WriteLine("Invalid entry. Type a number or Quit");
}
}
}
else if (input == "quit")
{
// input for a was invalid number, but 'quit'
op = eOperator.opQuit;
}
else
{
// input for a was invalid number and also not 'quit'
Console.WriteLine("Invalid entry. Type a number or Quit");
}
// repeat until the user wants to quit.
}while(op != eOperator.opQuit);
Console.WriteLine("Bye");
}
}

how do I loop this code so I can add to the total cost value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How do I loop this code so I can add to the total cost value?
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Workshop_Selector
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calculateBtn_Click(object sender, EventArgs e)
{
// Declaring variables to zero so they can found in a list
decimal registrationFee = 0;
decimal days = 0;
decimal lodgingFee = 0;
if (workshopListBox.SelectedIndex != -1 && locationListBox.SelectedIndex != -1) //when list items selected are not below zero
{
//From workshop list data inputs calculate the variables
switch (workshopListBox.SelectedIndex)
{
case 0: // in the first case of "Handling Stress" the workshop lasts for 3 days and costs 1000 euro
days = 3;
registrationFee = 1000;
break; //Case finisher
case 1: // in the second case of "Time Mgnt" the workshop lasts for 3 days and costs 800 euro
days = 3;
registrationFee = 800;
break;
case 2: // in the third case of "Supervision skills" the workshop lasts for 3 days and costs 1500 euro
days = 3;
registrationFee = 1500;
break;
case 3: // in the fourth case of "Negotiation" the workshop lasts for 5 days and costs 1300 euro
days = 5;
registrationFee = 1300;
break;
case 4: // in the fifth case of "How to Interview" the workshop lasts for 3 days and costs 500 euro
days = 1;
registrationFee = 500;
break;
}
//From location list data inputs calculate the variables
switch (locationListBox.SelectedIndex)
{
case 0: //In the first case in the location list lodging fee per day in Galway is 150 euro
lodgingFee = 150;
break;
case 1: //In the second case in the location list lodging fee per day in Dublin is 225 euro
lodgingFee = 225;
break;
case 2: //In the third case in the location list lodging fee per day in Limerick is 175 euro
lodgingFee = 175;
break;
case 3: //In the fourth case in the location list lodging fee per day in Cork is 300 euro
lodgingFee = 300;
break;
case 4: //In the fifth case in the location list lodging fee per day in Athlone is 175 euro
lodgingFee = 175;
break;
case 5: //In the sixth case in the location list lodging fee per day in Ennis is 150 euro
lodgingFee = 150;
break;
}
}
//end of if statements and variables
// Illustrate results
costLabel.Text = "Registration: " + registrationFee.ToString("c") +
" \nLodging Fee: " + lodgingFee.ToString("c") + " x " +
days.ToString() + " days = " + (lodgingFee * days).ToString("c");
totalCostTextBox.Text = (registrationFee + (lodgingFee * days)).ToString("c");
}
}
}
add this code:
private void totalCostTextBox_TextChanged(object sender, EventArgs e)
{
if (totalCostTextBox.Text == "€ 0,00")
MessageBox.Show("hey!");
}
if you simply don't want the Userform to go on, then add at the bottom of calculateBtn_Click():
//end of if statements and variables
// Illustrate results
costLabel.Text = "Registration: " + registrationFee.ToString("c") +
" \nLodging Fee: " + lodgingFee.ToString("c") + " x " +
days.ToString() + " days = " + (lodgingFee * days).ToString("c");
decimal totalCost = registrationFee + (lodgingFee * days);
if (totalCost == 0)
{
MessageBox.Show("total cost was zero! Re-Enter data");
}
else
{
totalCostTextBox.Text = totalCost.ToString("c");
}
and so the user will have to re-enter valid data and have textbox populated

C# Use of unassigned local variable [duplicate]

This question already has answers here:
c# switch problem
(8 answers)
Closed 6 years ago.
I am trying to do make a basic program in C# that calculates netPay and grossPay, however I am running into a little problem. I included a switch to set my taxRate to a const based off of a letter provided, after I added the switch into my program it says taxRate is an unassigned local variable. I am still very new to C# so I probably made a very simple mistake but for the life of me I cant find it. thanks in advance for the help.
const int married = 15, single = 22, divorced = 23, widowed = 13;
double payRate, hoursWorked, grossPay, netPay;
double taxRate;
char marStatus;
Console.WriteLine("Please Enter Hourly Wages");
payRate = int.Parse(Console.ReadLine());
Console.WriteLine("Please Enter Hours Worked");
hoursWorked = int.Parse(Console.ReadLine());
Console.WriteLine("Please Enter Marital Status Letter: (M) Married (S) Single (D) Divorced (W) Widowed");
marStatus =Convert.ToChar(Console.ReadLine());
switch (marStatus)
{
case 'M':
taxRate = married;
break;
case 'S':
taxRate = single;
break;
case 'D':
taxRate = divorced;
break;
case 'W':
taxRate = widowed;
break;
default:
Console.WriteLine("Invalid Input, Please Try Again.");
break;
}
if (hoursWorked > 40)
{grossPay =((hoursWorked-40)*(payRate*1.5))+(40*payRate);}
else
{ grossPay = payRate * hoursWorked; }
netPay = grossPay * taxRate; // This is where I have the problem
Console.WriteLine("Gross Pay=" +grossPay);
Console.WriteLine("Net Pay=" +netPay);
Console.WriteLine("xxx");
Console.ReadLine();
in the switch-case, if the defual case is met (no other case matches "marStatus"), then taxRate doesn't get asigned with a value. later you try to use this variable, with no value. this is the compilation error you're getting. asign a value to the variable.

My Loop is not working - it exits before it should

I'm new to programming. I tried this code and the loop is not working. The console application just ends after one operation, and I would like to continue doing more until I choose to say "no." Where am I making a mistake here? I want the program to keep going until I say so. Thanks in advance.
static void Main(string[] args)
{
Console.WriteLine("Program to convert USA Dollars to five different currencies,");
Console.WriteLine();
double dollars, euros, turkisLira, yen, britishPounds, mexicanPeso;
char option;
euros = 0.72;
turkisLira = 2.09;
yen = 101.73;
britishPounds = 0.59;
mexicanPeso = 13.03;
string answer = "Y";
do
{
Console.Write("Enter the Amount of USA Dollars to Convert:");
dollars = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("1.Convert to Euros");
Console.WriteLine("2.Convert to Turkis Lira");
Console.WriteLine("3.Convert to Japanes Yen");
Console.WriteLine("4.Convert to British Pounds");
Console.WriteLine("5.Convert to Mexican Pesos");
Console.Write("Enter the option of Currency you wish to convert : ");
option = Convert.ToChar(Console.ReadLine());
switch (option)
{
case '1':
euros = dollars * euros;
Console.WriteLine("The amount of Euros given is : {0}", euros);
break;
case '2':
turkisLira = dollars * turkisLira;
Console.WriteLine("The amount of Turkis Liras given is : {0}", turkisLira);
break;
case '3':
yen = dollars * yen;
Console.WriteLine("The amount of Japanes Yen given is : {0}", yen);
break;
case '4':
britishPounds = dollars * britishPounds;
Console.WriteLine("The amount of British Pounds given is : {0}", britishPounds);
break;
case '5':
mexicanPeso = dollars * mexicanPeso;
Console.WriteLine("The amount of Mexican Pesos given is : {0}", mexicanPeso);
break;
}
Console.WriteLine(" Do you wish to do more conversions? (yes/no)");
answer = Console.ReadLine();
if (answer.Equals("Y"))
{
Console.WriteLine("Yes");
}
else if (answer.Equals("N"))
{
Console.WriteLine("No");
}
} while (answer.ToLower() == "y'");
Your requirement is
I will like to continue doing more until I choose to say No
while your exist condition is
(answer.ToLower() == "y'");
So, if somebody clicks anything other than y, the loop would exit. You would want the exist condition to be
(answer.ToLower() != "n'");-
I think you have miss type ' in "y'" where you just want receive "y" to continue.

Categories

Resources