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.");
}
}
Related
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 ..
I need to calculate years and months from a given number. how can I do it?
eg:
I am giving: 26
I need to get result: 2 years 2months
please help
Unless you have some more specific requirements, it should be as easy as Integer Division and the Remainder operator %
var input = 26;
var years = input / 12;
var months = input % 12;
Console.WriteLine($"{years} years and {months} months");
Output
2 years and 2 months
or
private static (int Years, int Months) GetYearsAndMonths(int input)
=> (input / 12, input % 12);
...
var result = GetYearsAndMonths(26);
Console.WriteLine($"{result.Years} years and {result.Months} months");
or the little known method Math.DivRem Method as supplied by #Charlieface
Calculates the quotient of two numbers and also returns the remainder
in an output parameter.
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.
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);
}
}
I'm fairly new to programming in general but have been working with Java for the past 2-3 months and decided to take a crack at C# on the side just for fun because I heard they were similar. The problem I'm having with this program, which is just a way for someone to convert an int to a percentage, is that it takes all my input correctly but the percentage always shows up as zero! For example, there are two input prompts: one that asks you for a number for converting and one that asks you what the number is out of. After both prompts the program displays correctly "Your percentage is: " and then just writes 0 no matter what numbers I use for input, help please!
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NumToPercentage
{
class Program
{
static void Main(string[] args)
{
int userScore, userTotalScore, userPercentage;
string userInput, userTotal;
Console.WriteLine("Welcome to the number to percentile conversion program!");
Console.WriteLine("Please enter your number here: ");
userInput = Console.ReadLine();
userScore = int.Parse(userInput);
Console.WriteLine("Please enter what the number is out of (i.e. 100, 42, 37, etc.): ");
userTotal = Console.ReadLine();
userTotalScore = int.Parse(userTotal);
userPercentage = (userScore/userTotalScore)*100;
Console.WriteLine("Your percentage is: " + userPercentage);
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
}
}
[/code]
The problem is integer math, it rounds towards zero.
1 divided by 100 is 0.
99 divided by 100 is 0.
199 divided by 100 is 1.
Convert at least one of the operands to a floating point type (double, float, decimal) when you perform your calculation.
double result = ((double)x / y) * 100;
If needed, you can always cast the result back to an integer if you are uninterested in the decimal places.
int finalPercent = (int)result;
userPercentage = (int)((double)userScore/userTotalScore)*100);
or
userPercentage = (userScore * 100) / userTotalScore;
int/int is an integer division and only returns the whole part which is always 0 for a percentage, which then multiplied by 0 equals... 0
(userScore/userTotalScore)*100;
dividing two integers will result in an integer value. It chops off the fraction.
Instead, do this
(int)( ( (double) userScore )/userTotalScore)*100 );
By utilizing type casting, you can get the result you are looking for.
You need to use decimals instead of ints. Integer division behaves different than floating point division.
Change your declarations to:
decimal userScore, userTotalScore, userPercentage;
And then later:
userScore = decimal.Parse(userInput);
And
userTotalScore = decimal.Parse(userTotal);
Because you declare your vars as int, you're performing an integer division.
You need to declare userPercentage as a double instead of int and cast the userScore and userTotalScore to double before performing the division.