Subtraction between multiple random input numbers - c#

i want to make user input random number example : 5-3-10-50
, system will split " - " and then the result 5 3 10 50
, how to make subtraction from first number minus second number and so on,
like this 5 - 3 = 2 , 2 - 10 = -8 , -8 - 50 = -58
and then system will print the final answer -58
my code :
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out _))
{
double NumberResult = Convert.ToDouble(result);
Answer -= NumberResult;
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
i know my code is wrong, im beginner i already try to fix this but i cant fix it until now, i hope someone tell me what's wrong with my code and fix it too, thank you.

The reason yours doesn't work is because you set Answer = 0.
And you used foreach. On the first iteration of the loop, the first number is subtracted from Answer which results in -5.
Use for (int i=1; i<arr.Length; i++)
instead of foreach
Start from index 1, and then subtract the values.
Example:
var arr = InputNumber.Split('-');
double Answer = 0;
if (double.TryParse(arr[0], out _))
{
// We set Answer to the first number, since nothing is subtracted yet
Answer = Convert.ToDouble(arr[0]);
}
// We start index from 1, since subtraction starts from 2nd number on the String array
for (int i=1; i<arr.Length; i++)
{
if (double.TryParse(arr[i], out _))
{
double NumberResult = Convert.ToDouble(arr[i]);
Answer -= NumberResult;
}
}
Tested on Online C# Compiler

You would need a condition inside the foreach loop to check for the first parsed double before you begin subtraction. Also there is no need to call Convert.ToDouble() since the double.TryParse() function already returns the parsed double value, All you would need is a variable to contain the out value of the double.TryParse() function, See example below
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
double numResult;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out numResult))
{
if(Math.Abs(Answer)>0){
Answer -= numResult;
}
else{
Answer=numResult;
}
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}

Related

Why does the average only output the sum and then add the same value for 8th input and when there is only 7 entries

I am just trying to output the average of a case entry form. The case entry form is suppose to take only 7 inputs and convert it to a double and output the average of all the inputs but my average is not working. I am not too sure. Every time I try to use sum += userInput; and then move onto the if statement which calculates the average, it only outputs either all the numbers added together or some arbitrary number. I have tried just using the number 7 instead of the MaxDays constant which is 7. I am suppose to output the average to the user in a label. I have asked colleagues and look at reddit, youtube videos, other questions related to this issue but it does not really pertain to my issue.
Here is the code.
private void Enter_Click(object sender, EventArgs e)
{
bool isValid;
isValid = ValidateInfections();
double userInput;
if (double.TryParse(textBoxCaseEntry.Text, out userInput))
{
using TryParse.
if (userInput >= 0 && userInput <= int.MaxValue)
{
listBoxCases.Items.Add(textBoxCaseEntry.Text);
labelDay.Text = "Day " + (listBoxCases.Items.Count + 1);
for (int p = 0; p <= MaxDays; p++)
{
sum += userInput;
if (listBoxCases.Items.Count == MaxDays)
{
double dailyAverage = sum / MaxDays ;
labelAverageDailyCases.Text = "The daily case average is " + dailyAverage.ToString();
textBoxCaseEntry.Enabled = false;
Enter.Enabled = false;
}
}
}
}
else
{
MessageBox.Show("Calculations can not be performed as one or more validations have failed");
SetDefaults();
}
}

Iteration issues using Linear Search

In my code I have to run through some files with a load of numbers in and at some point need the user to input a number to see if it is in the file or not , if it is in the file then the returning output should be the positioning of where in the file. If it is not in the list then I need to return the closest value to their input. Eg 669 is in the list however 668 is not. My code is as follows for a function to find the nearest value:
static int nearest(int close_num, int[] a)
{
int result = -1;
long smallestDelta = long.MaxValue;
foreach (int bob in a)
{
long delta = (bob > close_num) ? (bob - close_num) : (close_num - bob);
if (delta < smallestDelta)
{
smallestDelta = delta;
result = bob;
}
}
return result;
Then the linear search and the rest is as follows :
Console.WriteLine("Enter a number to find out if is in the selected Net File: ");
int i3 = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < a.Length; i++)//looping through array
{
if (a[i] == i3)//checking to see the value is found in the array
{
Console.WriteLine("Value found and the position of it in the selected Net File is: " + i, a[i]);
break;
}
else
{
int found = nearest(i3, a);
Console.WriteLine("Cannot find this number in the Net File however here the closest number to that: " + found);
However these are my outputs:[Output 1 : Entering a value that is the file , for some reason prints the else call 3x before , if I remove the break in the code it just breaks. 1
Output 2: Prints whilst running through the whole list of values
how can I fix these formatting issues bc the code is doing what I need it to , just not in a way it should.
Thanks

Making a simple calculator with arrays in C#

I am trying to make a simple calculator with arrays in C#. Firstly I tried making it using two integers and one operator only and it worked well. Now I am trying to do so that the user can make the expression as long as they like. For example 7 * 7 + 1 / 50 instead of a simple 9 + 8 which includes only one operator and two integers. The problem is that whenever I type a long expression with multiple numbers and operators it only calculates the first 2 numbers with the first operator. What is a good fix for this problem ? Thanks in advance.
static void Main()
{
while (true)
{
Console.WriteLine("Write an expression with two numbers and an operator with space in-between, for example, 4 + 2");
string expression;
string[] array;
string[] array1;
expression = Console.ReadLine();
array = expression.Split();
array1 = Calculation(array);
Console.WriteLine("Press ENTER to write a new expression.");
Console.ReadLine();
Console.Clear();
}
}
static string[] Calculation(string[] arr)
{
double numLeft= 0.0;
double numRight = 0.0;
string sign = "";
double result = 0.0;
int index = 1;
while (true)
{
numLeft = Convert.ToDouble(arr[0]);
sign = Convert.ToString(arr[index]);
numRight = Convert.ToDouble(arr[index + 1]);
index = index + 2;
if (sign == "+")
{
Console.Clear();
Console.WriteLine();
result= result + numLeft;
}
else if (sign == "-")
{
Console.Clear();
result = result + numLeft;
numLeft = 0 - numRight;
}
else if (sign == "*")
{
Console.Clear();
numLeft = numLeft * numRight;
}
else if (sign == "/")
{
Console.Clear();
numLeft = numLeft / numRight;
}
else
{
break;
}
result = result + numLeft;
Console.WriteLine("Answer: {0}", result);
return arr;
}
return arr;
}
because you return the array at the end of the "while true", so only first 2 get calculated.
Also, this will not be correct. for example: 2 + 3 * 4 = 14, and not 20, like your calculator will calculate.
How about this?
Split your operation string into pieces and fill a list with them;
7 * 7 + 1 / 50 => [7][*][7][+][1][/][50]
Then go through the list and solve the * and / operations. When you encounter one of the operators remove the operator element, the one before it and the one after it, and replace them with the result. Keep in mind that the list length changes.
first iteration => [49][+][1][/][50]
second iteration => [49][+][0.02]
Then do the same for + and - operators
first iteration => [49.02]
When you have only one element remaining in the list, that is your result.
For simple computations there exists a method in .net:
public static int Compute(string operation)
{
return new DataTable().Compute("7 * 7 + 1 / 50", null);
}
Source: C# Math calculator
If you really want to implement this I would suggest a recursive binary tree algorithm.
Pseudo-code:
1. Split incoming string on places where there is a mathematical operation symbol and turn in to a binary tree
2. Go through this tree and resolve operations that have a greater priority (* comes before +)
3. Recursion should return value of two child leafs and so on until it yields only one value to the main program
using System;
namespace _2nd_A_recap
{
class Program
{
static void Main(string[] args)
{
int result;
int a = 20, b = 10;
result = (a + b );
Console.WriteLine("Addition Opertaor:" + result);
result = (a - b);
Console.WriteLine("Subtraction Operator:" + result);
result = (a * b);
Console.WriteLine("Multiplication Operator:" + result);
result = (a / b);
Console.WriteLine("Division Operator:" + result);
result = (a % b);
Console.WriteLine("Modulus Operator:" + result);
Console.WriteLine("Press enter to end Calculator...");
Console.ReadKey();
}
}
}

Binary to Decimal Conversion doesn't work

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();
}
}

Finding out whether a number is a palindrome or not in C#

I am new to C# and was doing this program as an exercise. I have managed to get my program to print the reversed number of the input given by the user, but when I move onto checking whether it is a palindrome or not, it does not calculate the answer correctly. It always prints 'not a palindrome'.
After some error checking, I realized that the reason why it was doing this is because the last number that gets stored in newnum is just the last digit after being reversed and not the entire number. How can I rectify this??
My Code
int i, remainder = 0, newnum = 0;
Console.WriteLine("Enter a Number: ");
int uinput = Convert.ToInt32((Console.ReadLine()));
for (i = uinput; i > 0; i = (i / 10))
{
remainder = i % 10;
Console.Write(remainder);
newnum = remainder;
}
if (newnum == uinput)
{
Console.WriteLine("The Number {0} is a palindrome", uinput);
}
else
{
Console.WriteLine("Number is not a palidrome");
}
Console.WriteLine(uinput);
Console.WriteLine(newnum);
Console.ReadKey();
}
I also looked online at another code example, but the thing I don't understand in that is why num is being converted to boolean type in the while loop? Is that just to keep the loop running?
The Code reffered to above
int num, rem, sum = 0, temp;
//clrscr();
Console.WriteLine("\n >>>> To Find a Number is Palindrome or not <<<< ");
Console.Write("\n Enter a number: ");
num = Convert.ToInt32(Console.ReadLine());
temp = num;
while (Convert.ToBoolean(num))
{
rem = num % 10; //for getting remainder by dividing with 10
num = num / 10; //for getting quotient by dividing with 10
sum = sum * 10 + rem; /*multiplying the sum with 10 and adding
remainder*/
}
Console.WriteLine("\n The Reversed Number is: {0} \n", sum);
if (temp == sum) //checking whether the reversed number is equal to entered number
{
Console.WriteLine("\n Number is Palindrome \n\n");
}
else
{
Console.WriteLine("\n Number is not a palindrome \n\n");
}
Console.ReadLine();
Any sort of help is much appreciated!! Thank You :)
I'm not sure what you're asking, since the second snippet of code you found online should fix your issue.
Your code works, if you just change the line
newnum = remainder;
to
newnum = (newnum*10) + remainder;
The issue in your case is not the condition you used in the for loop, it's just that you're overwriting newnum with the remainder every time, so newnum is only storing the last reminder that was calculated in the loop, "forgetting" all the others it had calculated before.
To reverse the number, every time you enter the loop, you should add the last remainder you've found to the right of newnum, which is effectively equivalent to multiplying everything by 10 and adding remainder.
Try to follow it step by step with pen and paper (or with a debugger).
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i<sNum.Length; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
I think that will do it... Untested!!
As dognose (and Eren) correctly assert you only need to go halfway through
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i < sNum.Length/2; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
You will also need to decide what happend to negative numbers.. ie is -121 a plaindome? This method will say that it isn't...
Easiest way:
public static Boolean isPalindrom(Int32 number){
char[] n1 = number.ToString().ToCharArray();
char[] n2 = number.ToString().ToCharArray();
Array.Reverse(n2);
String s1 = new String(n1);
String s2 = new String(n2);
return (s1 == s2);
}
https://dotnetfiddle.net/HQduT5
you could also use Integers for s1 and s2 and return (s1-s2 == 0)
You have many ways of accomplish this exercise.
A. You can leave the input as string and loop it over, every iteration to check if the value of index 'i' and value of index 'len-i-1' are equals, if not false, otherwise return at the end of the loop true. (the loop should run till i < len/2)
B. You can create a new string and insert the text from end to start and then compare if the original string and result string are equals.
C. there are much more ways without using the string solutions, just with calculation..
int x;
cin<<x; //input the number
int ar[];
int i=0;
temp2=0;
while(x/10 != 0)
{
int temp=x%10;
ar[i]=temp;
x=x/10;
i++;
}
for(int j=0, j<i,j++)
{
temp2=temp2*10+ar[j];
}
if(temp2==x){cout<<"palindrome"}
else {"not palindrome"}
ok here is the logic:
we first input the number x(it can be of any length)..Next we split the number into array..the condition to do this is tha we check for the qoutient to decide whether the number is fully split..next we take the array and rejoin it and check with the input number..
Use the following code:
public boolean isPalindrom(Integer number)
{
return number.Equals(int.Parse(String.Join("", String.Join("", number.ToString().ToCharArray().Reverse().ToArray()))));
}

Categories

Resources