I have some lines of code like this.
can anyone explain for me why "while loop" does not stop. it is keeping shows the result more than the balance.
static void Main(string[] args)
{
const double balance = 303.91;
const double phonePrice = 99.99;
double a = 0;
while (a < balance )
{
a = a + phonePrice;
}
Console.WriteLine(a);
Console.ReadLine();
}
It does exactly what you have written.
The loop ends when a is bigger than balance and then you print that a variable
If you expect to stop the loop BEFORE running out of money then you need to change the loop exit condition
static void Main(string[] args)
{
const double balance = 303.91;
const double phonePrice = 99.99;
double a = 0;
// You don't want to run out of money, so check if buying
// another phone will bankrupt your finances....
while ((a + phonePrice) < balance )
{
a = a + phonePrice;
}
Console.WriteLine(a); // a = 299,97
Console.ReadLine();
}
you are checking the value after add so it add first then check if a greater than balanceor not so one time extra phoneprice is added with a. Make your while loop
while ((a + phonePrice) < balance)
{
a = a + phonePrice;
}
Related
when I enter 1 for n
and 1111 for lines
the sum must be 1+1+1+1=4 but the output is 1.
THIS IS THE QUESTION...
you will get a (n) then (n) lines as an input, In each line there are some numbers (we don’t know how many they are) and you must print (n) lines, In the i-th line print the sum of numbers in the i-th line.
using System;
namespace prom2
{
class Program
{
static void Main(string[] args)
{
int lines=0, sum = 0;
Console.Write("Enter a number of lines ");
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n&n>0&1000>n; i++)
{
Console.WriteLine("Enter line " + i + " numbers");
lines = int.Parse(Console.ReadLine());
lines = lines / 10;
sum += lines % 10;
Console.WriteLine("sum is " + sum);
}
}
}
}
Try this:
static void Main(string[] args)
{
int input;
bool times = true;
List<int> numbers = new List<int>();
while (times)
{
Console.Clear();
Console.WriteLine("Enter number: ");
var num = int.TryParse(Console.ReadLine(), out input);//tryparse will output a bool into num and set input to a int
if (num)
{
numbers.Add(input);//only integers will be added to list
}
Console.Clear();
Console.WriteLine("Another? Y or N");//ask if they want to sum more numbers
var yesno = Console.ReadLine();//get answer from user
if (yesno.ToUpper().Trim() != "Y")//if N or anything else
{
//assume no
times = false;
}
Console.Clear();
}
var sum = numbers.Sum();
Console.WriteLine("Sum : " + sum.ToString());
Console.ReadLine();//just to pause screen
}
Because Console.ReadLine returns a string, and it's possible to treat a string as if it's an array of chars (where char represents a single character), you can have a method like this to calculate the sum of all the digits in a single line:
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
Please note this method contains no validation - ideally you should validate that line is purely numeric, otherwise int.Parse will throw an exception, although the same is true of the code you provided too.
If you want to work with multiple lines of console input, just call this method from within another loop which solicits / works through those lines of console input.
Edit
My answer doesn't answer all of your question, it only answers the part which asks how to calculate the sum of the digits in a numeric string, and it does work, to the extent that it correctly does what it says on the tin.
Here's all the code I wrote to validate the answer before posting the original answer (I wrote it as a xUnit unit test rather than a console application, but that doesn't change the fact that the code I shared works):
using System;
using Xunit;
namespace StackOverflow71442136SumDigits
{
public class UnitTest1
{
[Theory]
[InlineData("1", 1)]
[InlineData("12", 3)]
[InlineData("23", 5)]
[InlineData("1234", 10)]
[InlineData("123456789", 45)]
public void Test1(string line, int expectedSum)
{
var actualSum = this.SumTheDigits(line);
Assert.Equal(expectedSum, actualSum);
}
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
}
}
You might want to read How do I ask and answer homework questions?
So my code is to check if a given number is a 'happy number'. It squares each digit of the number, adds them and continues to do so until either the result of the addition is 1 (which means it is a happy number) or until it results in a 4 (which means it is not a happy number).
What's happening is that there are many numbers which cause an infinite loop (therefore meaning they are not a happy number) and I'm wondering how I would construct my code so that it will detect when there's an infinite loop occuring? I have some ideas but all flawed.
My code is as follows:
using System;
namespace Happy_numbers_problem
{
class Program
{
static int HappyNumbers(string Number)
{
string Output = Number;
while ((Convert.ToInt32(Output) != 1) && (Convert.ToInt32(Output) != 4))
{
string Result2 = "0";
for (int Index = 0; Index < Output.Length; Index++)
{
string Character = Output.Substring(Index, 1);
int Calc = Convert.ToInt32(Character);
int Result = Calc * Calc;
//Adding Result2 and Result, then turning it into a string.
Result2 = Convert.ToString(Convert.ToInt32(Result2) + Result);
if (Index == (Output.Length) - 1)
{
Output = Result2;
}
}
}
return Convert.ToInt32(Output);
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
string Number = Console.ReadLine();
int Output = HappyNumbers(Number);
if (Output == 1)
{
Console.WriteLine(Number + " is a happy number");
}
else if (Output == 4)
{
Console.WriteLine(Number + " is not a happy number");
}
else
{
Console.WriteLine(Number + " is not a happy number");
}
}
}
}
The problem resides in your while condition. If your output needs to be 1 or 4 to break out of the loop and deliver the output to latter be analysed, you have to use the operator or || instead of the operator and &&.
I have made bisection method program in C# Console Application. Bisection method works, but for function which is already written in the code. I want to edit program that user can input function which they want to use for bisection method. For example Console.ReadLine() for input "x^2 + x - 2" and then I want it automatically written after return in the code below.
static double Function(double x)
{
return x*x - 2;
} //this is Function which I used in code.
Here is the whole code. (as i mentioned it works for function which is written in static double Function(double x) part
using System;
namespace MPI
{
class MainClass
{
public static void Main(string[] args)
{
// in [a,b]
double inPoc = 0; //a
double inKraj = 0; //b
double sredina = 0;
double tacnost = 0;
Start:
int i = 0; //brojac
Console.Write("Unesite početak intervala: ");
inPoc = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite kraj intervala: ");
inKraj = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite tacnost: ");
tacnost = Convert.ToDouble(Console.ReadLine());
sredina = (inPoc + inKraj) / 2;
if (Function(inPoc) * Function(inKraj) < 0)
{
while ((Math.Abs(inPoc - inKraj)) > tacnost)
{
sredina = (inPoc + inKraj) / 2;
Console.WriteLine("trenutno X: " + sredina);
Console.WriteLine("Funkcija za trenutno x ima vrednost: " + Function(sredina));
Console.WriteLine("");
i++;
if (Function(sredina) < 0)
{
inPoc = sredina;
}
else
{
inKraj = sredina;
}
}
Console.WriteLine("X: " + sredina);
Console.WriteLine("Broj izvrsenih koraka je " + i);
}
else
{
Console.WriteLine("Krajevi intervala funkcije su istog znaka");
Console.WriteLine();
}
goto Start; //sluzi da vrati program na pocetak kako bi ga opet koristili
}
static double Function(double x)
{
return x*x - 2; //primer funkcije
}
}
}
Looks like this question is asking about the same.
There are two solutions to do this:
Solution 1 - just use Flee.
Copy-paste from documentation:
ExpressionContext context = new ExpressionContext();
VariableCollection variables = context.Variables;
variables.Add("a", 100);
variables.Add("b", 1);
variables.Add("c", 24);
IGenericExpression<bool> e = context.CompileGeneric<bool>("(a = 100 OR b > 0) AND c <> 2");
bool result = e.Evaluate();
So you can do the same, just change input/output types and put your input line into the CompileGeneric
Solution 2 - parse input string manually.
So question can be divided to the two parts:
How to parse input string into the expression tree.
How to execute this tree.
For the first item - please check reverse polish notation. It allows to construct computation stack.
Next you will able to compute your expression tree. Each operand (after trimming) will have variable or integer constant. So just replace variable to the actual value and just parse string to the integer.
I wrote a basic number guessing game from C#. It seems to return the 3rd option ("Wrong choice! Please try again.") every time no matter what var c is chosen by the user. I was trying with characters (s instead of 1 and w instead of 2 etc with c as a string) but it gave the same results. Not sure where it's going bad.
using System;
namespace Challanges
{
class Program
{
static int guess = 500;
static int low = 1;
static int high = 1000;
static bool cont = false;
static void Guess() //guesses and adjusts variables according to input.
{
int c;
Console.WriteLine("Is your number greater or less than: " + guess + Environment.NewLine + "If it is less than, press 1; if it is greater, press 2." + Environment.NewLine + "If it is your number, press 3.");
c = Convert.ToInt32(Console.Read());
if (c == 1)
{
high = 500;
guess = low + high / 2;
}
else if (c == 2)
{
low = 500;
guess = low + high / 2;
}
else if (c == 3)
{
Console.WriteLine("Congratulations!! We found your number!");
cont = true;
}
else
{
Console.WriteLine("Wrong choice! Please try again.");
Console.ReadKey();
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!" + Environment.NewLine + "Let's play a guessing game. Think of a number between 1 and 1000." + Environment.NewLine + "Type your number :)");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your number is: " + x + Environment.NewLine + "Too easy?");
Console.ReadKey();
Console.WriteLine("Think of a number");
if(cont == false)
{
Guess();
} else
{
Console.ReadKey();
}
}
}
}
As mentioned in the comments before, Console.Read() returns a character code. The character code for the number 1 is 49, thus your conditions fail and the else block is executed.
What you wanted to do was use Console.ReadLine()which returns a string instead of character codes. If you cast that string into an Int32 you should be able to evaluate your conditions correctly.
It tells me that it can't convert int to bool.
Tried TryParse but for some reason the argument list is invalid.
Code:
private void SetNumber(string n)
{
// if user input is a number then
if (int.Parse(n))
{
// if user input is negative
if (h < 0)
{
// assign absolute version of user input
number = Math.Abs(n);
}
else
{
// else assign user input
number = n;
}
}
else
{
number = 0; // if user input is not an int then set number to 0
}
}
You were probably very close using TryParse, but I'm guessing you forgot the out keyword on the parameter:
int value;
if (int.TryParse(n, out value))
{
}
Just use this:
int i;
bool success = int.TryParse(n, out i);
if the parse was successful, success is true.
If that case i contain the number.
You probably got the out argument modifier wrong before. It has the out modifier to indicate that it is a value that gets initialized within the method called.
You can try with some simple regular expression :
bool IsNumber(string text)
{
Regex regex = new Regex(#"^[-+]?[0-9]*\.?[0-9]+$");
return regex.IsMatch(text);
}
private void SetNumber(string n)
{
int nVal = 0;
if (int.TryParse(n, out nVal))
{
if (nVal < 0)
number = Math.Abs(nVal);
else
number = nVal;
}
else
number = 0;
}
There are a lot of problems with this code:
Using VB-style line comments (') instead of C# slashes
Parse for integer returns an int and not a bool
You should use TryParse with an out value
h does not seem to be valid at all. Is it a type for n?
There are variables that do not seem to be defined in function scope (number) are they defined at class scope?
But try this:
private void SetNumber(string n)
{
int myInt;
if (int.TryParse(n, out myInt)) //if user input is a number then
{
if (myInt < 0) //if user input is negative
number = Math.Abs(n); //assign absolute version of user input
else //else assign user input
number = n;
}
else number = 0; //if user input is not an int then set number to 0
}
You could try something like below using int.TryParse..
private void SetNumber(string n)
{
int parsed = -1;
if (int.TryParse(n, out parsed)) //if user input is a number then
...
The reason there are complaints that it cannot convert an int to a bool is because the return type of int.Parse() is an int and not a bool and in c# conditionals need to evaluate bool values.
int.Parse will give you back an integer rather than a boolean.
You could use int.TryParse as you suggested.
int parsedValue;
if(int.TryParse(n, out parsedValue))
{
}
Well for one thing the inner if statement has an 'h' instead of an 'n' if(h < 0). But TryParse should work there assuming that 'number' is a class variable.
private void SetNumber(string n)
{
int temp;
bool success = Int32.TryParse(n, out temp);
// If conversion successful
if (success)
{
// If user input is negative
if (temp < 0)
number = Math.Abs(temp); // Assign absolute version of user input
else // Assign user input
number = temp;
}
else
{
number = 0;
}
}
int.Parse will convert a string to an integer. Current you have it within an if statement, so its treating the returned value of int.Parse as a bool, which its not.
Something like this will work:
private void SetNumber(string n)
{
int num = 0;
try{
num = int.Parse(n);
number = Math.Abs(num);
}catch(Exception e){
number = 0;
}
}
I did this in the simplest way I knew how.
static void Main(string[] args)
{
string a, b;
int f1, f2, x, y;
Console.WriteLine("Enter two inputs");
a = Convert.ToString(Console.ReadLine());
b = Console.ReadLine();
f1 = find(a);
f2 = find(b);
if (f1 == 0 && f2 == 0)
{
x = Convert.ToInt32(a);
y = Convert.ToInt32(b);
Console.WriteLine("Two inputs r number \n so tha additon of these text box is= " + (x + y).ToString());
}
else
Console.WriteLine("One or tho inputs r string \n so tha concadination of these text box is = " + (a + b));
Console.ReadKey();
}
static int find(string s)
{
string s1 = "";
int f;
for (int i = 0; i < s.Length; i++)
for (int j = 0; j <= 9; j++)
{
string c = j.ToString();
if (c[0] == s[i])
{
s1 += c[0];
}
}
if (s==s1)
f= 0;
else
f= 1;
return f;
}