nested if statement in C# [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I get the command prompt to come up and get the correct answer for Bad Score, but if I try to type in a good grade (800) it does nothing. Any help would be greatly appreciated. I am new to this so I apologize my coder isn't pretty.
//variables
string firstName, lastName, grades = "";
double points = 0, percent = 0;
//Greeting
Console.WriteLine("The purpose of this program is to allow the teacher to calculate the percentage and final grade for students in their class.");
//Display and Inputs
Console.WriteLine("\n\nPlease enter the students first name.");
firstName = Console.ReadLine();
Console.WriteLine("\n\nPlease enter the students last name.");
lastName = Console.ReadLine();
Console.WriteLine("\n\nPlease enter the points that the student received.\n\n");
points = Convert.ToDouble(Console.ReadLine());
//Display after points are entered
if (points < 0 || points > 1000 )
{
Console.WriteLine("Bad Score!");
}
else
{
percent = points / 1000;
if (percent >= .9)
{
grades = "A";
}
else if (percent >= .8)
{
grades = "B";
}
if (percent >= .7)
{
grades = "C";
}
else if (percent >= .6)
{
grades = "D";
}
if (percent >= .0)
{
grades = "F";
}
else
{
Console.WriteLine("WRONG!!");
}
}
grades = Console.ReadLine();
//Outputs
Console.WriteLine(firstName);
Console.WriteLine(lastName);
Console.WriteLine(points);
Console.WriteLine(percent.ToString("P"));
Console.WriteLine("so they made an" + grades);
//Closing statement
Console.WriteLine("Goodbye");
Environment.Exit(1);
}
}
}

Suppose you enter
first name - Puneet
last name - Chawla
Enter the points students received -
800
10
Then answer is
Puneet
Chawla
800
80.00 %
so they made an10
Goodbye
When this condition will be false if (points < 0 || points > 1000) then you are giving grade according to percent i think, you don't need to get grade again from user.
In some conditions, wrong output can come because you have set
Wrong - if,elseif, if,elseif,if then else
Correct - if,elseif,elseif,elseif,elseif then else.

You've got a bunch of problems
You are missing an else before the 'C' and 'F' branches. Currently, all positive grades will become 'F's
else if (percent >= .7)
{
grades = "C";
}
And again
else if (percent >= .0)
{
grades = "F";
}
You are then overwriting your calculated grades with this line
grades = Console.ReadLine();
I believe you may have intended:
Console.WriteLine(grades);
Your app will exit after the calculation. I suggest a Console.ReadLine at or similar at the end to allow the user to view the results

You are getting the grades variable correcty. But at the end of the ifs statements you are overriding its value, so just remove this line:
grades = Console.ReadLine();
PS: Also you could chain all ifs statements with else if

Your pgms have two problems at first glance
Your if..else is wrong inside the else it should be
else
{
percent = points / 1000;
if (percent >= .9)
{
grades = "A";
}
else if (percent >= .8)
{
grades = "B";
}
else if (percent >= .7)
{
grades = "C";
}
else if (percent >= .6)
{
grades = "D";
}
else if (percent >= .0)
{
grades = "F";
}
else
{
Console.WriteLine("WRONG!!");
}
}
you are missing else at checking if percent >= 0.7 and percent >=.0
let say you entered 800 so percentage will be 0.8 so the condition if percent >=.08 will be true and grade ="B" and since there is no else at percent >= 0.7 it will also pass and grade will become "c" atlast there is no else while checking percent >= .0 so it will also pass and grade will become "F" so else is needed in all condition. So finally what ever the positive percentage is there the grade will be "F" because of missing else..in the if conditions
you should remove grade = Consolde.ReadLine(); because it will overwrite your assign in grade.

Related

I've made a code for a assignment but i need a push in the right direction [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 10 months ago.
Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
i need your guidance for this assignment:
At TEC Ballerup Stadium with room for 500 spectators, football matches are played every Sunday at 10.00. It is amateurs who play and it costs to watch the matches. There is access for adults and children, also spectators who are not members of the club (members of the club get a 10% discount!) A children's ticket costs DKK 30. An adult ticket costs DKK 65. Children only have access with an adult. first enter how many adult tickets and then how many children's tickets you want to buy. There must be a good guide so that the user of the program is not in doubt about what to enter.
a. Once the price has been calculated and displayed, the program must ask if you are a member of the club's association group. Here you can answer yes or no.
b. If you are a member, you get a discount of 10%. Print the discount.
c. There must be two loops (one for each entry of the number of tickets) so that you can order a maximum of 10 children's tickets and 10 adult tickets.
d. Make a printout that also tells how many tickets you have bought in total. So children and adult tickets together.
e. Some individual foreign spectators would like to pay in Euros. Modify the program so that it can also print the total price in EUR. Expect the course at the moment. is 757.34. Make sure to round to the whole Euro as we can not give back in foreign currency.
f. Add Date so that the application always prints the current date at the top right of the screen
So far i've coded this:
int maxNumber = 500;
int revenueSum = 0;
string adultBillet;
string childrenBillet;
int numberOrdered;
string numberOrderedString;
// How many adult tickets?
Console.WriteLine ("number of adult tickets");
Console.Write ("how many do you want?");
adultBillet = Console.ReadLine ();
// how many child tickets?
Console.WriteLine ("number of child tickets");
Console.Write ("how many do you want?");
childrenBillet = Console.ReadLine ();
String selection = "1";
while (choice! = "9")
{
Console.WriteLine ("How many adult tickets do you want ??");
numberOrdered = Convert.ToInt32 (Console.ReadLine ());
if (numberOrdered == 0)
{
Console.WriteLine ("You will need to purchase at least 1 ticket.");
}
else if (number Ordered> 10)
{
Console.WriteLine ("maximum number of adult tickets is 10.");
}
else if (numberOrdered> maxNumber)
{
Console.WriteLine ($ "Only {quantityOrder} left");
}
else
{
Console.WriteLine ($ "You have decided to purchase {number of Ordered} adult tickets");
}
Console.WriteLine ("are you a club member?");
Console.WriteLine ("please answer YES or NO");
String Club MemberReply = Console.ReadLine (). ToUpper ();
if (Club Member Answer == "YES")
{
Console.Write (numberOrdered * 65 * 0.9);
}
else if (Club MemberReply == "NO")
{
Console.Write(AmountofTickets * 65);
}
else
{
Console.WriteLine("Invalid answer");
i'm stuck on what to do now? It's all, all over the place, but uh I guess I need a loop for adulttickets and kidstickets and how many tickets in total and the euros and dkk's and finally the date
I made a demo for you according to your request, just for your reference.
You can use the following code to set a size for the console first.
Console.SetWindowSize(100, 50);
Console.SetBufferSize(100, 50);
Use this to output the date
Console.CursorLeft = Console.BufferWidth - 10;
Console.Write("{0}\n", DateTime.Now.ToString("yyyy-MM-dd"));
Use int.TryParse to prevent users from entering incorrect information.
There are two main cycles, the purchase of adult tickets for the big cycle and the purchase of children's tickets for the small cycle.
The judgment condition is simpler. Entering the specified character is regarded as yes, otherwise it is regarded as no.
Below is my code:
using System;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
double adultPrice = 65, kidPrice = 30, totalPrices = 0;
int tmpTickets = 0, adultTickets = 0, kidsTickets = 0, totalTickets = 0, EurPrices = 0;
bool adultSuccess = false, kidSuccess = false;
Console.SetWindowSize(100, 50);
Console.SetBufferSize(100, 50);
Console.CursorLeft = Console.BufferWidth - 10;
Console.Write("{0}\n", DateTime.Now.ToString("yyyy-MM-dd"));
Console.WriteLine("Welcome Ticket Mall!\n" +
"AdultPrice 65 DKK,childrenPrice 30 DKK.\n" +
"You can order a maximum of 10 children's tickets and 10 adult tickets.\n" +
"A child enters with an adult, so the child ticket cannot be larger than the adult ticket.");
while (!adultSuccess)
{
Console.WriteLine("Please enter the number of adult tickets.");
if (adultSuccess = int.TryParse(Console.ReadLine(), out tmpTickets))
{
if (tmpTickets < 0 || tmpTickets > 10)
{
Console.WriteLine("input error!please enter again!");
adultSuccess = false;
}
else if (tmpTickets == 0)
{
Console.WriteLine("Thanks for using, bye.");
}
else
{
adultTickets = tmpTickets;
Console.WriteLine("Do you need to buy a child ticket?\n" +
"Enter 'Y' or 'y' to go to the next step.");
string tmp = Console.ReadLine();
if (tmp != "Y" && tmp != "y")
{
break;
}
else
{
while (!kidSuccess)
{
Console.WriteLine("Please enter the number of kids tickets.");
if (kidSuccess = int.TryParse(Console.ReadLine(), out tmpTickets))
{
if (tmpTickets < 0 || tmpTickets > adultTickets)
{
Console.WriteLine("input error!please enter again!");
kidSuccess = false;
}
else
{
kidsTickets = tmpTickets;
}
}
}
}
}
}
}
Console.Clear();
Console.CursorLeft = Console.BufferWidth - 10;
Console.Write("{0}\n", DateTime.Now.ToString("yyyy-MM-dd"));
totalPrices = adultTickets * adultPrice + kidsTickets * kidPrice;
totalTickets = adultTickets + kidsTickets;
Console.WriteLine($"You have decided to purchase {adultTickets} adult tickets {kidsTickets} kid tickets\n" +
$"Total {totalTickets} tickets , {totalPrices} DKK ");
Console.WriteLine("are you a club member?\n" +
"Enter 'Y' or 'y' as a member.");
var tmp2 = Console.ReadLine();
if (tmp2 != "Y" && tmp2 != "y")
{
//1 Danish Krone is equal to 0.13 EUR now
EurPrices = Convert.ToInt32(totalPrices * 0.13);
Console.WriteLine($"You need to pay {totalPrices} DKK or {EurPrices} EUR! ");
}
else
{
totalPrices = totalPrices * 0.9;
EurPrices = Convert.ToInt32(totalPrices * 0.13);
Console.WriteLine($"As a member! You need to pay {totalPrices} DKK or {EurPrices} EUR !");
}
//Pause
Console.ReadLine();
}
}
}
Here is a screenshot of my demo:

Random number guessing game not working C# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to get this random number guessing game working. The program runs, but it doesn't give the "you won" message when you enter the correct number, and the hint feature does not give the feed back it is supposed to. Any help appreciated.
using System;
namespace randomNumberGame
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
var val = r.Next(1, 100);
var guess = 0;
bool correct = false;
var attemptsLeft = 5;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (!correct && attemptsLeft >= 1)
{
Console.Write("You have " + attemptsLeft + " lives left. Please enter your Guess: ");
string input = Console.ReadLine();
var message = "";
var difference = val - guess;
if (!int.TryParse(input, out guess))
{
Console.WriteLine("That's not a number.");
continue;
}
if (difference == 0)
{
Console.WriteLine("You have won");
correct = true;
}
else
{
if (Math.Abs(difference) >= 50)
{
message = Math.Sign(difference) == -1 ? "Very High" : "Very Low";
}
else if (Math.Abs(difference) < 50 && Math.Abs(difference) >= 20)
{
message = Math.Sign(difference) == -1 ? "High" : "Low";
}
else if (Math.Abs(difference) < 20 && Math.Abs(difference) >= 10)
{
message = Math.Sign(difference) == -1 ? "Moderatley High" : "Moderately Low";
}
else if (Math.Abs(difference) < 10)
{
message = Math.Sign(difference) == -1 ? "Somewhat High" : "Somewhat Low";
}
else Console.WriteLine("???");
}
attemptsLeft--;
}
}
}
}
"it doesn't give the you won message when you enter the correct number"
Actually, it does! But then the program exits so quickly that you never see it. To solve this, add a line that waits for the user to press a key at the end of your Main method, so you can see the final result:
// Add this as the last line of the main method:
Console.ReadKey();
"the hint feature does not give the feed back it is supposed too"
This is because you never output the hint message! At the end of your while loop, add a line to do so:
// Add this as the last line of the while loop:
Console.WriteLine(message);
These things can be found easily if you simply set a breakpoint in your code (in Vistal Studio, click the left margin next to one of the lines and a red dot will appear (or press F9)). Then you can step through the code using F10 and you can watch the values of local variables change and see what is happening step-by-step.
Another way to help avoid problems (and to narrow down where they occur) is to take out chunks of code that does something specific and put it in a method. This will make it easier to debug in the long run.
For example, we can write methods that take in a string to display to the user as a prompt for input, and return a strongly-typed value based on their entry. We can also have these methods take in an optional validation method that can be used to validate that the input they entered falls within a valid range (like a number from 1 to 100, or a name that's not longer than 25 characters):
public static string GetStringFromUser(string prompt,
Func<string, bool> validator = null)
{
string result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
result = Console.ReadLine();
} while (!(validator?.Invoke(result) ?? true));
return result;
}
public static int GetIntFromUser(string prompt,
Func<int, bool> validator = null)
{
int result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
!(validator?.Invoke(result) ?? true));
return result;
}
private static void ClearSpecificLineAndWrite(int cursorTop,
string message)
{
Console.SetCursorPosition(0, cursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, cursorTop);
Console.Write(message);
}
We can also write a helper method to get our "difference string", which could take in the guess, the number, and the min and max values, then calculate a percentage of how close they were and then return the appropriate string:
public static string GetDifferenceString(int guess, int number,
int minVal, int maxVal)
{
var percentAway =
Math.Abs(guess - number) / (double)(maxVal - minVal) * 100;
var direction = guess - number > 0 ? "High" : "Low";
if (percentAway < 10) return $"Very close, but {direction}";
if (percentAway < 20) return $"Just a little {direction}";
if (percentAway < 30) return $"Somewhat {direction}";
if (percentAway < 40) return $"Moderately {direction}";
if (percentAway < 50) return $"{direction}";
return $"Very {direction}";
}
This simplifies our main code by removing the loops and checking results from there, and lets us focus on our main tasks:
static void Main(string[] args)
{
var randomNumber = new Random().Next(1, 101);
var maxAttempts = 5;
var guess = 0;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
Console.WriteLine($"You have {maxAttempts - attempt} " +
$"out of {maxAttempts} attempts remaining.");
guess = GetIntFromUser("Please enter your guess (1 - 100): ",
i => i > 0 && i < 101);
if (guess == randomNumber)
{
Console.WriteLine($"You have won in {attempt + 1} tries!");
break;
}
Console.WriteLine(GetDifferenceString(guess, randomNumber, 1, 100));
}
if (guess != randomNumber)
{
Console.WriteLine("Sorry, you lose! The number was: " +
$"{randomNumber}");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}

C# output letter grade from a range using doubles

It appears my teacher wants the class to use double to solve this problem. I am having difficulty getting it to take. I'm sure it's someting simple that I'm missing but I want to see what others think.
public char Test4(double grade)
{
// TODO: Write code here to compute an answer.
// Return the answer from this function.
// Read the lab document for detailed instructions.
}
I've tried using if else statements and to no luck. I'm not sure how to use a double for this. Please help.
Thanks.
Here's an example of what I've tried.
if (grade >= 90 && grade <= 100)
{
public char = 'A'
}
else if (grade >=80 && grade <90)
{
public char = 'B'
}
return public char;
{
The output:
I've cleaned this up. Hope this helps to clarify the question.
public char Test4(double grade)
{
// TODO: Write code here to compute an answer.
// Return the answer from this function.
// Read the lab document for detailed instructions.
if (grade >= 90.0)
{ return 'A'; }
else
if (grade >= 80.0)
{ return 'B'; }
else
if (grade >= 73.0)
{ return 'C'; }
else
if (grade >=70.0)
{ return 'D'; }
else
if (grade >= 0)
{ return 'F'; }
else
if (grade <0 )
{ return '?'; }
else
if (grade > 100)
{ return '?'; }
}
You are returning "public char", you need to either return it in place, or store the value in a variable.
example 1
if (grade >= 90)
{
return 'A';
}
else if ....
{
//copy for each letter grade above F
}
else
{
return 'F';
}
example 2
char gradeLetter = 'F';
if (grade >= 90)
{
gradeLetter = 'A';
}
else if ....
{
//copy for each letter grade above F
}
return gradeLetter;
I don't think that you compile with Test4 as written and are running and old, unimplemented version of Test4 (hence no results). You have an error, which I'm guessing is: "not all code paths return a value." To solve this, have a "catch all" at the end - you don't need to check if grade is <0 AND >100, just return ?.
...
else if(grade >= 0)
{
return 'F';
}
// if none of the if statements were hit, you have an incorrect grade value
return '?';
This is should properly compile Test4 (note, you have an error with Test5 that needs to be fixed as well) and give you the correct results.

Novice to C#: How to use methods? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am a novice programmer and I am working in visual studio using C#. In a Windows Form Application, Create a form that gets the input from a user from 0-100. You will need to make 3 methods for this application. Your first method must get the users input and validates that the entry is valid. Use logic to ensure the input is accurate, if the user enters an invalid entry throw a message box to the user with the error. The user must have a successful entry to proceed. We will expand on validation and exceptions in Lab 5. Once the score is validated send the score to a second method which assigns a letter grade. Use the following grading schema and use integer values for your scoring. < 60 is a F, >= 60 and < 70
is a D, >= 70 and < 80 is a C, >= 80 and < 90 is a B, >= 90 is an A. Once a grade is assigned pass the score and the letter grade to a Third Method. The third method will handle display and concatenate the results into a single string as displayed in the image below.
This is what I currently have...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lab4_Part_1_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnValidate_Click(object sender, EventArgs e)
{
//Set user input to integer.
int score = Convert.ToInt32(txtScore.Text);
Form1 moto = new Form1();
lblGrade.Text = moto.NumEnter(score);
}
private string NumEnter(int score)
{
string result;
//Set parameters for user input and prompt with textbox if outside parameters.
if (score < 0 | score > 100)
{
MessageBox.Show("Enter a score 0-100.");
this.txtScore.Text = "";
}
//Set parameters for each letter grade
else if (score >= 0 && score <= 100)
{
if (score >= 90)
{
result = lblGrade.Text = "A";
}
else if (score >= 80)
{
result = lblGrade.Text = "B";
}
else if (score >= 70)
{
result = lblGrade.Text = "C";
}
else if (score >= 60)
{
result = lblGrade.Text = "D";
}
else
{
result = lblGrade.Text = "F";
}
return result;
}
//Concatenate the input user score and output a message with the letter grade.
lblGrade.Text = "You entered an " + txtScore.Text + " which is a " +
lblGrade.Text + " letter grade.";
}
}
}
"Use at least X methods" = "Don't do everything in one big method." That is all.
For example, instead of this huge method:
private string NumEnter(int score)
{
string result;
//Set parameters for user input and prompt with textbox if outside parameters.
if (score < 0 | score > 100)
{
MessageBox.Show("Enter a score 0-100.");
this.txtScore.Text = "";
}
//Set parameters for each letter grade
else if (score >= 0 && score <= 100)
{
if (score >= 90)
{
result = lblGrade.Text = "A";
}
else if (score >= 80)
{
result = lblGrade.Text = "B";
}
else if (score >= 70)
{
result = lblGrade.Text = "C";
}
else if (score >= 60)
{
result = lblGrade.Text = "D";
}
else
{
result = lblGrade.Text = "F";
}
return result;
}
//Concatenate the input user score and output a message with the letter grade.
lblGrade.Text = "You entered an " + txtScore.Text + " which is a " +
lblGrade.Text + " letter grade.";
}
You could instead break it down into four short methods:
private string GetLetterGrade(int score)
{
if (score < 0 | score > 100)
{
return null; //not valid score
}
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "F";
}
private string NumEnter(int score)
{
var grade = GetLetterGrade(score);
if (grade == null)
{
MessageBox.Show("Enter a score 0-100.");
ClearUserInput();
return;
}
DisplayScore(score, grade);
}
public void ClearUserInput()
{
this.txtScore.Text = "";
}
public void DisplayScore(int score, string grade)
{
this.lblGrade.Text = String.Format("You entered an {0} which is a {1}", score, grade);
}
As a rule, programmers should try to break things down into smaller methods. This practice greatly reduces complexity and makes the code easier to read (Some engineers would actually state a hard rule that no method should ever be bigger than a single screen.)
Also, introducing more methods means introducing more method names, which allows a programmer to quickly understand the purpose of the code without needing to read code comments-- from my code snippet, for example, it is very clear what is intended by calling ClearUserInput and DisplayScore, without having to dig into the code inside those functions, and without understanding the purpose of the textboxes on the form. Not a big deal in this exercise but extremely helpful in real-world applications, where there may be dozens of controls on the form.
See also
Functions Should Be Short And Sweet, But Why?
The art of writing small and plain functions
Can a function be too short?
Change:
Form1 moto = new Form1();
lblGrade.Text = moto.NumEnter(score);
to:
lblGrade.Text = NumEnter(score);
There is no need to new up a new Form1 since your code is already running in a Form1.
You should also change your lines like:
result = lblGrade.Text = "A";
to just return the result:
return "A";
And let btnValidate_Click take care of setting lblGrade.Text.

Check the length of integer variable

Is there a way to check a lenth of integer variable, and if is to long just trim it.
I hava a field in database that accepts 3 character, lenth is 3.
So is it possible to do like it's done with string variable
example:
cust_ref = cust_ref.Length > 20 ? cust_ref.Substring(0, 19) : cust_ref;
Thanks!
The easiest answer would be:
//The length would be 3 chars.
public int myint = 111;
myint.ToString().Length;
The following worked a treat for me!
public static int IntLength(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if (i == 0)
return 1;
return (int)Math.Floor(Math.Log10(i)) + 1;
}
Original Source: http://www.java2s.com/Code/CSharp/Data-Types/Getthedigitlengthofanintvalue.htm
You don't have to convert it to a string to make it shorter, that can be done numerically:
if (num > 999) {
num %= 1000;
}
This will cut of digits from the left, if you want to cut them off from the right:
while (num > 999) {
num /= 10;
}
If the value can be negative, also check:
if (num < -99) {
num = -(-num % 100);
}
or:
while (num < -99) {
num = -(-num / 10);
}
cust_ref = cust_ref.ToString().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
or simply use
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
Use like this
cust_ref= cust_ref.Tostring().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
Nont very clear what you're asking for, but as much as I unerstood you're asking for:
int a = 1234567890;
for some reason you want to make it shorter, like
int b = MakeShorter(a);
//b == 1234 (say)
If so, the easiest solution may be, convert it to string, made what you already implemented and reconvert it back to int.
If this is not what you're asking for, please clarify.
The conversion to the string is ugly way to implement it.
It's require a pure math solution
int CutTheNumber(int number, int maxLen)
{
var maxSize = (int)Math.Pow(10, maxlen);
if(maxSize <= Math.Abs(number))
{
number %= maxSize;
}
return number;
}
Checking length
length = cust_ref.ToString().Length;
Remove extra bits
if (length > need)
{
cust_ref =Convert.ToInt32( cust_ref.ToString().Remove(length -(length- need)));
}
for this u will have to do some simple stuffs.
like
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
or u can manually store it in any variable and the
You can try this code. use if else statement to check the validation ..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace avaragescore
{
class Program
{
static void Main(string[] args)
{
float quiz;
float midterm;
float final;
float avrg=0;
Start:
Console.WriteLine("Please enter the Quize Score here");
quiz = float.Parse(Console.ReadLine());
if(quiz > 100)
{
Console.WriteLine("You have entered wrong score please re-enter");
goto Start;
}
Start1:
Console.WriteLine("Please enter the Midterm Score here");
midterm = float.Parse(Console.ReadLine());
if(midterm > 100)
{
Console.WriteLine("You have entered wrong score please re- enter");
goto Start1;
}
Start3:
Console.WriteLine("Please enter the Final Score here");
final = float.Parse(Console.ReadLine());
if(final > 100)
{
Console.WriteLine("You have entered wrong Score Please re-enter");
goto Start3;
}
avrg = (quiz + midterm + final) / 3;
if(avrg >= 90)
{
Console.WriteLine("Your Score is {0} , You got A grade",avrg);
}
else if (avrg >= 70 && avrg < 90)
{
Console.WriteLine("Your Score is {0} , You got B grade", avrg);
}
else if (avrg >= 50 && avrg < 70)
{
Console.WriteLine("Your Score is {0} , You got C grade", avrg);
}
else if (avrg < 50)
{
Console.WriteLine("Yor Score is {0} , You are fail", avrg);
}
else
{
Console.WriteLine("You enter invalid Score");
}
Console.ReadLine();
}
}
}

Categories