Why are results rounding down ? (C#) [duplicate] - c#

This question already has answers here:
How can I divide two integers to get a double?
(9 answers)
Closed last year.
I'm a beginner trying to make a very basic calculator.
I have a problem with division, though;
For some reasons, the result is always rounded down not matter what:
Console.WriteLine("First Argument ?");
int Arg1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second argument ?");```
int Arg2 = Convert.ToInt32(Console.ReadLine());
float OpDiv = Arg1 / Arg2;
Console.WriteLine($"The result is {OpDiv}");
For example here, 11 / 3 returns 3, instead of 3.66666666...
What have I done wrong ???

Change to:
Console.WriteLine("First Argument ?");
int Arg1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second argument ?");
int Arg2 = Convert.ToInt32(Console.ReadLine());
float OpDiv = (float)Arg1 / Arg2;
Console.WriteLine($"The result is {OpDiv}");

Related

How do I fix "is a variable but is used like a type [New folder]"?

I recently started learning c# and I want the user to input a two-digit number and then the console to multiply the two-digit number (first digit * second digit) and then the console to find out if it's an even or an odd number.
//user type question
int first1;
int second2;
Console.WriteLine("type a digit");
first1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("type a second digit");
second2 = Convert.ToInt32(Console.ReadLine());
Console.ReadKey();
//the answer
int result = multiplied(first1, second2);
Console.WriteLine("the result is " + result);
if (result % 2 == 0)
{
Console.WriteLine("it is an even number");
}
else
{
Console.WriteLine("it is an odd number");
}
//machine
int multiplied (first1, second2)
{
int result = first1 * second2;
return result;
}
The errors are:
Argument 1: cannot convert from 'int' to 'first1' [New folder]
Argument 2: cannot convert from 'int' to 'second2' [New folder]
'first1' is a variable but is used like a type [New folder]
Identifier expected [New folder]
'second2' is a variable but is used like a type [New folder]
Identifier expected [New folder]
Your multiplied function is missing the parameter types
You need to explicitly state the data types of parameters which you pass in a method. So you need to change your code like this:
int multiplied (int first1, int second2)
{
int result = first1 * second2;
return result;
}

Problems with formatting decimals in c# [duplicate]

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 8 months ago.
I'm trying to create a simple C# program (I'm a beginner) to convert days to weeks, months and years. However, the answer always appears in integers, not decimals. For example: 1200 days are equivalent to 3.2876 years, but the program returns only 3. I am using VSCode and .NET 6.0. I tried some output formatting but only got 3.00. Here is the code:
static void Main(string[] args)
{
string aux="";
int daysEntrada=0;
decimal monthSaida, yearsSaida, weeksSaida;
Console.WriteLine("-----------------------------");
Console.WriteLine("days conversor!");
Console.Write("Enter the number of days: ");
Console.WriteLine("\n-----------------------------");
Console.Write("-> ");
aux = Console.ReadLine();
bool isInteiro = int.TryParse(aux, out daysEntrada);
if(isInteiro == true){
daysEntrada = int.Parse(aux);
monthSaida = daysEntrada/30;
yearsSaida = daysEntrada/365;
weeksSaida = daysEntrada/7;
Console.WriteLine($"{daysEntrada} days is equal to: {daysEntrada} days, {weeksSaida} weeks, {monthSaida} months ans {yearsSaida} years.");
}else{
Console.WriteLine("Error, type again.");
}
}
The output generates:
days conversor!
Enter the number of days:
-----------------------------
-> 1200
1200 days is equal to: 1.200,00 days, 171 weeks, 40 months ans 3,00 years
The following is a rule that is valid in C, C++, C# and many more:
Division of two integers gives an integer so when you divide daysEntrada by 365 it returns the floor of the division( for example if it is 3.2876 it returns 3 if it's 3.99 it returns 3).
The solution in C# is to cast any of the values to decimal, I'm no expert in C# but this might work:
yearsSaida = daysEntrada/(decimal)365;
Also an useful article:
How can I divide two integers to get a double?
Try using floats instead of ints and decimals. The original error was caused because your original data type was int so when you divided it it returned an int (non decimal). Here I used floats for all the data types as that way you don't have to cast any values (from int to decimal).
Like this (changes were commented):
public static void Main(string[] args)
{
string aux="";
float daysEntrada=0; // changed from int to float
float monthSaida, yearsSaida, weeksSaida; // changed from decimal to float
Console.WriteLine("-----------------------------");
Console.WriteLine("days conversor!");
Console.Write("Enter the number of days: ");
Console.WriteLine("\n-----------------------------");
Console.Write("-> ");
aux = Console.ReadLine();
bool isInteiro = float.TryParse(aux, out daysEntrada); // changed from int.tryparse to float.tryparse
if(isInteiro == true){
daysEntrada = float.Parse(aux); //changed from int to float
monthSaida = daysEntrada/30;
yearsSaida = daysEntrada/365;
weeksSaida = daysEntrada/7;
Console.WriteLine($"{daysEntrada} days is equal to: {daysEntrada} days, {weeksSaida} weeks, {monthSaida} months ans {yearsSaida} years.");
}else{
Console.WriteLine("Error, type again.");
}
}

Sum of two double numbers [duplicate]

This question already has answers here:
How do I parse a string with a decimal point to a double?
(19 answers)
Closed 2 years ago.
Console.Write("First Number: ");
double n1 = double.Parse(Console.ReadLine());
Console.Write("Second Number: ");
double n2 = double.Parse(Console.ReadLine());
double r = n1+n2;
Console.WriteLine($"The result r are {r}");
When I input, for example:
2.3 and 5.2, the output is that r equals to 23 + 52 = 75, and not 7.5.
Why?
What version of .NET framework are you using? Example you gave works fine when run on .NET 5.
What crossed my mind is that the runtime takes localization into account and doesn't look for . as decimal point and ignores it instead. Maybe it looks for ,.
What you can try is passing some other localization setting to a parser like so
double.TryParse(Console.ReadLine(), NumberStyles.Number, CultureInfo.CreateSpecificCulture ("en-US"), out temp)
This should work with ..

Is there a function that swaps two variables in a string? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So we have to have code that swaps the integers in a two-digit number, such as "43" being "34". The user inputs a random two digit number and that number must be swapped.
I am not sure how to separate or mess with the two digit number that the user inputs into the console, so I have not had much luck in doing this.
static void Main(string[] args)
{
Console.WriteLine("Please enter a two-digit integer");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
Console.ReadKey();
}
You can also just reverse the string before you parse it:
string input = string.Concat(Console.ReadLine().Reverse());
// If the user entered "34", 'input' will equal "43"
You can try modulo arithmetics:
number = number % 10 * 10 + number / 10;
you could do:
Console.WriteLine("Enter a No. to reverse");
int Number = int.Parse(Console.ReadLine());
int Reverse = 0;
while(Number>0)
{
int remainder = Number % 10;
Reverse = (Reverse * 10) + remainder;
Number = Number / 10;
}
Console.WriteLine("Reverse No. is {0}",Reverse);
Console.ReadLine();
this will give you 34 if you entered 43.
You can checkout this https://www.c-sharpcorner.com/blogs/reverse-a-number-and-string-in-c-sharp1 for more info.

c# console application unassigned local variable [duplicate]

This question already has answers here:
What does "Use of unassigned local variable" mean? [duplicate]
(11 answers)
Closed 7 years ago.
int ValueOne, ValueTwo, Numchar, Total;
Console.WriteLine("This Is A Program For doing any Of the four mathematical Proccesses");
Console.WriteLine("You can Add , substract , Divide And Multiply");
Console.WriteLine("When Asked Please Type The Values Or The Proccesses You Want.");
Console.WriteLine("Please Type The First Value");
ValueOne = Convert.ToInt32((Console.ReadLine()));
Console.WriteLine("Please Type The Second Value");
ValueTwo = Convert.ToInt32((Console.ReadLine()));
Console.WriteLine("Please Enter The Number Of The Proccess/Character You Want Meaning That (1 = +) , (2 = -) , (3 = *) , (4 = /)");
Numchar = Convert.ToInt32((Console.ReadLine()));
if (Numchar == 1)
Total = ValueOne + ValueTwo;
if (Numchar == 2)
Total = ValueOne + ValueTwo;
if (Numchar == 3)
Total = ValueOne * ValueTwo;
if (Numchar == 4)
Total = ValueOne / ValueTwo;
Console.WriteLine("The Total Is :");
Console.WriteLine(Total);
Console.ReadLine();
the Console.WriteLine(Total);
at the end is apparently an unassigned local variable , though it should be assigned from the Lines beneath the "If" lines, also note that I'm new in visual studio and i just started taking The Courses , also , i don't think this is a duplicate because the other post's fix Didn't Work for me.
Let's say that your code didn't produce an error, and compiled and ran. What do you think would happen if NumChar wasn't 1, 2, 3, or 4?
Your code would never reach any of the statements in your ifs there, and would never assign an initial value to Total. Since this is entirely possible given your program (and would be impossible to check for in general -- see the Halting Problem), the error is substantiated and necessary.

Categories