i have a problem the product of multiplying three numbers in my program, Even after BigInteger type.
I don't get any meaningful number.
Please check the code below:
using System;
using System.Numerics;
class Program
{
static void Main()
{
denss:
string density;
int den;
Console.WriteLine("Please enter the density value in kg/m3");
density = Console.ReadLine();
bool dens = int.TryParse(density, out den);
if (dens == false)
{
Console.WriteLine("Please enter numbers only");
goto denss;
}
Console.WriteLine(den);
velss:
string velocity;
int vel;
Console.WriteLine("Please enter the velocity value in m/s");
velocity = Console.ReadLine();
bool vels = int.TryParse(velocity, out vel);
if (vels == false)
{
Console.WriteLine("Please enter numbers only");
goto velss;
}
Console.WriteLine(vel);
lengt:
string length;
int len;
Console.WriteLine("Please enter the length value in m");
length = Console.ReadLine();
bool leng = int.TryParse(length, out len);
if (leng == false)
{
Console.WriteLine("Please enter numbers only");
goto lengt;
}
Console.WriteLine(len);
BigInteger rel = den * vel * len;
Console.WriteLine(rel);
if (rel>100000)
Console.WriteLine("turbuelent flow. Reynolds no is ", rel);
else
Console.WriteLine("laminar flow. Reynolds no is ", rel);
Console.ReadKey();
}
}
The output i get is shown in this photo:enter image description here
Amongst other issues, your main problem is the following line:
BigInteger rel = den * vel * len;
What is happening here is den * vel * len is calculated as an int because all values involved are int. This int overflows and is meaningless. This meaningless number is then assigned to the BigInteger rel. What you need is:
BigInteger rel = new BigInteger(den) * new BigInteger(vel) * new BigInteger(len);
or declare them as double, which is what they should have been for this problem domain in the first place.
The code should be
if (rel>100000)
Console.WriteLine("turbuelent flow. Reynolds no is {0}", rel);
else
Console.WriteLine("laminar flow. Reynolds no is {0}", rel);
And please, don't use gotos
You aren't actually outputting the value on the console. The string that you use as the output (the first parameter to WriteLine) must contain a token showing where to insert the second parameter (the number) into the string. For example:
Console.WriteLine("turbuelent flow. Reynolds no is {0}", rel);
The {0} shows where the parameter should go. If you have multiple parameters to output, you can use {0}, {1}, and so on.
Actually, your code could be written a bit less repetitively like this:
string flowType = "";
if (rel > 100000) flowType = "turbulent";
else flowType = "laminar";
Console.WriteLine("{0} flow. Reynolds no is {1}", flowType, rel);
See https://msdn.microsoft.com/en-us/library/586y06yf(v=vs.110).aspx for more details.
Too many problems:
incorrect output Console.WriteLine("turbuelent flow. Reynolds no is ", rel); - {0} omitted
BigInteger rel = den * vel * len; prone to integer overflow
wrong types - why den, vel, len are integers? Why, say, len can't be 15 cm = 0.15 meters?
goto...
copy/paste
Let's do it right. First of all, decompose your solution, extract a method, do not copy/paste:
//DONE: double, not int - velocity, density and length are not necessary integers
private static double ReadValue(string title) {
double result = 0.0;
Console.WriteLine(title);
while (!double.TryParse(Console.ReadLine(), out result))
Console.WriteLine("Please enter numbers only");
return result;
}
Then implement a simple Main() without goto and other ugly things
static void Main() {
//DONE: double, not int:
// what if alcohol travels along a pipe:
// density = 856.96 kg/m3 (some reference value)
// velocity = 3.6 m/s (5 km/h)
// length (diameter?) = 0.015 m (1.5 cm)
double den = ReadValue("Please enter the density value in kg/m3");
double vel = ReadValue("Please enter the velocity value in m/s");
double len = ReadValue("Please enter the length value in m");
double rel = den * vel * len;
//DONE: use formatting not a complex logic
// F0 - we don't want anything after the decimal point, as if rel is integer
Console.WriteLine("{0} flow. Reynolds no is {1:F0}", // string
rel > 100000 ? "turbuelent" : "laminar", // 1st arg
rel); // 2nd arg
Console.ReadKey();
}
Related
(C# Visual Studio 2019) Hello, my professor wants us to do the following code shown in the picture :
https://i.stack.imgur.com/ONNSV.png
We are fairly new into the course and have have talked about only a few of conversion methods.
Here is my attempt, but with an error that I cannot seem to wrap my head around. If someone can help me out or provide a solution, thanks!
Console.Write("Enter degrees Fahrenheit to convert to Celsius OR \nenter degrees Celsius
to convert to Fahrenheit.");
Console.Write("\n\nCurrent temperature scale (C for Celsius; F for Fahrenheit): ");
double tempscale = Convert.ToDouble(Console.ReadLine());
Console.Write("Current degrees: ");
double currentdeg = Convert.ToDouble(Console.ReadLine());
double degreeCelsius = 5 / 9 * (tempscale - 32);
double degreeFahrenheit = 9 / 5 * (degreeCelsius + 32);
if (tempscale == degreeFahrenheit)
Console.Write(degreeFahrenheit + "degrees Fahrenheit is" + degreeCelsius + "degrees Celsius");
if (tempscale == degreeCelsius)
Console.Write(degreeCelsius + "degrees Celsius is" + degreeFahrenheit + "degrees Fahrenheit");
Console.Write("\n\nPress any key to continue...");
Console.ReadKey();
if you write 5 / 9 in your code, you are doing integer division which is a little different from what you expect:
int x = 5;
int y = 9;
int result = x / y; // result is 0
if you divide 2 integers the result is an integer and for integer division that results in a fraction the result is rounded towards zero (everything after the decimal sign is discarded)
try writing floating point literals either as 5f for a float or 5d for a double...
5d / 9d should do what you expected
Your first goal is to get C/F from user. Let's make simple method for it. It will return C or F, based on user input.
Or you could use enum.
enum TemperatureScales { Celsius, Fahrenheit }
Here is sample of method to get temperature scale.
private static char GetTemperatureScale()
{
// Will wait for correct input from user
while (true)
{
Console.WriteLine("Enter C or F");
var input = Console.ReadLine();
if (input == "C" || input == "F") // you could improve and check for 'c' and 'f'
{
return input[0]; // you could use enum here if you are familiar with it
}
}
}
Use it in your code to ensure valid input.
I need to invoke a method to then print it, right now i get .NaN as the output when you enter the right temperature.
using System;
using System.Security.Cryptography.X509Certificates;
namespace Bastun2
{
class Pogram
{
public static void Main(string[] args)
{
double temperatureF = double.NaN;
double temperatureC = double.NaN;
string input = string.Empty;
bool inputIsOkay = false;
while (!inputIsOkay) //Tells you to repeat until input is true
{
Console.WriteLine("Enter temperature in numbers."); //Asks for temperature
input = Console.ReadLine(); //Input temperature
if (!double.TryParse(input, out temperatureF)) //Prevents you for using letters
{
Console.WriteLine($"'{input}' is not a valid input. Use numbers and , not ."); //Tells you not to use letter or "."
}
else if (temperatureF < 163.4)//Repeat if temperature is under 163.4
{
//temperatureC = (temperatureF - 32) * 5 / 9; //Converts Farneheight to Celcius
Console.WriteLine($"Temperature is to low, enter a higher temperature."); //Tells you that temperature is to low and asks you to input a higher temperature
}
else if (temperatureF > 170.6)//Repeat if temperature is to high
{
//temperatureC = (temperatureF - 32) * 5 / 9; //Converts Farneheight to Celcius
Console.WriteLine($"Temperature is to high, enter a lower temperature.");//Tells you that temperature is to high and asks you to input a lower temperature
}
else
{
inputIsOkay = true; //kick you out of the loop if input is true
}
}
//temperatureC = (temperatureF - 32) * 5 / 9; //Converts Farneheight to Celcius
//Console.ReadLine(calculateC);
Console.WriteLine($"{temperatureC}°C, temperature is within acceptable parameters");//prints C and tell you that temperature is acceptable
}
public static double CToF(double temperatureF, double temperatureC)
{
temperatureC = (temperatureF - 32) * 5 / 9;
return temperatureC;
}
}
}
Based on your replies to the original, I can see an obvious problem from the get go. You're never setting the value for the temperatureC variable which is why you're always getting NaN as you're output when you're trying to print it.
You're already invoking a lot of methods by calling them such as Console.WriteLine(...), etc.
All you need to do is this at the bottom of the Main method under the while loop:
temperatureC = CToF(temperatureF, temperatureC);
And then output the value of temperatureC like you are doing with:
Console.WriteLine($"{temperatureC}°C, temperature is within acceptable parameters");
Another small suggestion to make your code a little more efficient as well as readable is to change your CToF method and just do this:
public static double CToF(double temperatureF)
{
return (temperatureF - 32) * 5 / 9;
}
If you decide to accept that idea of improvement, you can then just invoke the method like so:
temperatureC = CToF(temperatureF);
This is kind of a funky program. For some reason it works when the binary input is something like 101. Then it doesn't for 1000. This is kind of odd. Could someone please explain?
class Program
{
static void Main()
{
string binary = "xxx";
double decimalValue = 0;
Console.WriteLine("Enter in a binary number:");
binary = Console.ReadLine();
for (int i = 0; i < binary.Length; i++)
{
Console.WriteLine("Length is: {0}", binary.Length);
if (binary[i] == 49) //Look at that
decimalValue = decimalValue + Math.Pow(2, i);
}
Console.WriteLine("The decimal equivalent value is {0}", decimalValue);
Console.ReadLine();
}
}
The heart of it is of course
if (binary[i] == 49)
I'm just making it to teach myself some C#. Could someone tell me what to put on the right side other than 49, which is the ASCII number for "1". If I put "1" I get an error saying you can't compare a string to a char.
Any help would be appreciated. I don't want to use the pre-canned convert to binary method, because this is supposed to be a teachable moment.
You read the characters from the wrong end.
As was said immediately in the first comment to the question, by Lucas Trzesniewski, replace one use of i (not both) inside the for loop with binary.Length - 1 - i.
The reason why it works for "101" is that this is a palindrome (reads the same backwards).
Note: 49 is the ASCII code for '1'. It is more readable to use == '1' than == 49. However, both work equally well. In C# you get a char value if you use single quotes, as in '1', and you get a string object reference if you use double quotes, "1".
You should remove the stuff with "xxx". It has no function. Just dostring binary = Console.ReadLine();.
Instead of trying to add the value of each individual bit based on it's position you could take another approach: shift and add. In this approach you shift the current value to the left (by multiplying that value by 2) and adding the current bit.
For instance: the binary value 1010 becomes decimal 10 in four cycles:
value = 0
value *= 2 => value = 0
value += bit 1 => value = 1
value *= 2 => value = 2
value += bit 0 => value = 2
value *= 2 => value = 4
value += bit 1 => value = 5
value *= 2 => value = 10
value += bit 0 => value = 10
Or, in code:
using System;
public class Program
{
public static void Main()
{
string binary = "";
double decimalValue = 0;
Console.WriteLine("Enter in a binary number:");
binary = Console.ReadLine();
for (int i = 0; i < binary.Length; i++)
{
decimalValue *=2; // shift current value to the left
if (binary[i] == 49)
{
decimalValue += 1; // add current bit
}
Console.WriteLine("Current value: {0}", decimalValue);
}
Console.WriteLine("The decimal equivalent value is {0}", decimalValue);
Console.ReadLine();
}
}
I am receiving an error "Operator '*' cannot be applied to operands of type 'int' and 'decimal[]'", as I am attempting to multiply two values with different data types (one being a value located in an array). My question is how am I able to multiple numberOfMinutes * perMinuteRate in my code below? My variable is called total, which I declared a double data type (although may be incorrect).
I tried changing data types and played with formatting (like ToString), but I am not sure what to do. I also tried to google the answer with no success.
I am by no means a professional programmer; I'm not in school. I'm a data analyst who is learning to program.
Here is my code:
static void Main(string[] args)
{
int[] areaCodes = { 262, 414, 608, 715, 815, 920 };
decimal[] perMinuteRate = { .07m, .1m, .05m, .16m, .24m, .14m };
int numberOfMinutes;
int userAreaCode;
string inputString = "1";
while (inputString != "0")
{
int x;
Console.WriteLine("Enter the area code for your call (or 1 to end):");
inputString = Console.ReadLine();
userAreaCode = Convert.ToInt32(inputString);
Console.WriteLine("How many minutes will your call last?");
inputString = Console.ReadLine();
numberOfMinutes = Convert.ToInt32(inputString);
for (x = 0; x < areaCodes.Length; x++)
{
if (userAreaCode == areaCodes[x])
{
***double total = numberOfMinutes * perMinuteRate;***
Console.WriteLine("You call to {0} will cost {1} per minute for a total of {2}.", areaCodes[x], perMinuteRate[x].ToString("C"), total.ToString("C"));
x = areaCodes.Length;
}
}
if (x != areaCodes.Length)
{
Console.WriteLine("I'm sorry; we don't cover that area.");
inputString = "1";
}
else
{
Console.WriteLine("Thanks for being our customer.");
inputString = "0";
}
Console.ReadLine();
}
}
Thank you in advance.
Change:
double total = numberOfMinutes * perMinuteRate;
to
double total = (double)(numberOfMinutes * perMinuteRate[x]);
The same way you index into perMinuteRate in the line directly below.
The expression [int] * [decimal] will result in a decimal, and the cast (double) will convert it to a double
To avoid loss of precision, change it to:
decimal total = numberOfMinutes * perMinuteRate[x];
I'm pretty new to C# and am wondering how I'd go about validating user input to meet the following requirements:
has to be a decimal type. if it isn't it should ask the user to enter a decimal value. (Which i believe i have covered in my code below)
also has to be within a specific range (1 - 1,000,000). If it isn't it should ask the user to enter a number within the correct range
What's the most efficient way of doing this considering i will have multiple user input to validate in the same sort of way.
decimal balance;
Console.Write("Starting Balance: $");
while (!decimal.TryParse(Console.ReadLine(), out balance))
{
Console.Write("Please enter a valid decimal value: $");
}
EDITED BELOW
How about this?
decimal balance;
Console.Write("Starting Balance: $");
while(true)
{
if (!decimal.TryParse(Console.ReadLine(), out balance))
Console.Write("Please enter a valid decimal value: $");
else if (balance < 1 || balance > 100)
Console.Write("Please enter an amount between 1 and 100: ");
else
break;
}
Console.WriteLine("Balance entered is: " + balance.ToString("n"));
return val; line gave me an error so i left it out but the above seems to work?
I'd try something like:
decimal GetUserInput(string inputQuery, decimal min, decimal max)
{
Console.Write(inputQuery);
decimal val;
while(true)
{
if(!decimal.TryParse(Console.ReadLine(), out val))
Console.Write("Please enter a valid decimal value: $");
else if(val < min || val > max)
Console.Write("Please enter an amount between " + min + " and " + max + ": $");
else // the value is a decimal AND it's correct
break;
}
return val;
}
Then use it like:
var startingBalance = GetUserInput("Starting Balance: $", 1, 100000);
var endingBalance = GetUserInput("Ending Balance: $", 1, 100000);
//...
If your min and max are fixed, then you could not pass them as arguments and use a fixed check. And you could also avoid having the query : $ passed in if needed, but I'll leave that to you
Update
The reason why the return val line was giving you an error was because you were inlining it (probably in a void returning function). What I was doing was making a function since you specified it needed to be reusable.
So in your program, you need to make a separate function... your program would look something like this:
class Program
{
// We're declaring this function static so you can use it without an instance of the class
// This is a function, so it can be called multiple times, with different arguments
static decimal GetUserInput(string inputQuery, decimal min, decimal max)
{
// Write the argument "inputQuery" to console
Console.Write(inputQuery);
decimal val;
// Loop indefinitely
while(true)
{
// Read from console into a decimal "val"
if(!decimal.TryParse(Console.ReadLine(), out val))
// It was not a correct decimal, so write the prompt
Console.Write("Please enter a valid decimal value: $");
// It was a correct decimal
else if(val < min || val > max)
// But not in range, so write a different prompt
Console.Write("Please enter an amount between " + min + " and " + max + ": $");
// It was a decimal and within range
else
// so we break the infinite loop and exit after the "}"
break;
// If we have got to this point (we didn't hit the "break"),
// it was either not a decimal or it wasn't within range,
// so it'll loop again and ask for a value from console again.
// The prompt was already written above (in the "ifs")
}
// We got out of the while(true){} loop, so it means we hit "break"
// above, and that means "val" contains a correct value (decimal and
// within range), so we return it to the caller
return val;
}
static void Main()
{
// Your original code went here, but see how my function is *outside* function Main()
// You use my function (GetUserInput) here:
var startingBalance = GetUserInput("Starting Balance: $", 1, 100000);
var endingBalance = GetUserInput("Ending Balance: $", 1, 100000);
// Then with the returned values (stored in "startingBalance"
// and "endBalance"), you can do what you want:
Console.WriteLine("Starting balance was: " + startingBalance.ToString("n"));
}
}
I've made a fiddle with the whole program so you can test online and make changes: https://dotnetfiddle.net/HiwwIP
If I were you, I would do such:
bool isInvalid, isOutOfRange;
decimal balance = 0;
isOutOfRange = true;
do
{
string input = Console.ReadLine();
isInvalid = !Decimal.TryParse(input, out balance);
if (!isInvalid)
{
// use balance<=1 if 1 should not be included
// use balance>=1000000 if 1000000 should not be included
isOutOfRange = (balance < 1 || balance > 1000000);
}
if (isInvalid)
{
Console.WriteLine("Please enter a valid decimal value: $");
}
else if (isOutOfRange)
{
Console.WriteLine("Please enter value between 1 and 1000000: $");
}
} while (isInvalid || isOutOfRange);
Console.WriteLine("{0}, That is a valid value!", balance.ToString());
Console.ReadKey();
Of course you can shortcut by eliminating bool definitions and directly calling functions instead; but I wrote in detail for clarity as you indicated that you are "pretty new".