Console.Read() not work correctly - c#

int y = 0;
Console.WriteLine("insert x");
int x = Console.Read();
Console.WriteLine("insert n");
int n = Console.Read();
Console.WriteLine("insert a");
int a = Console.Read();
int sum = (2 * n - 1) * a;
int sum2 = (2 * n * a);
int sum3 = (2 * n + 1) * a;
if (x <= 0) y = 0;
else if (x > sum && x <= sum2) y = a;
else if (x > sum2 && x <= sum3 || n <= 3 || n >= 1) y = 0;
Console.WriteLine("Y = " + y);
Console.ReadLine();
}
can't insert all values. after i insert x y printed and console close, what is my mistake?

Instead of Read use ReadLine. Only then you can be sure the user actually pressed ENTER and the entire line is returned - Read blocks until the user presses ENTER, but then returns the ASCII code of only one character. If you read the documentation example, this becomes clear.
In your example, if you enter "1" and press ENTER, the next calls to Read will actually return the ASCII codes for 1, \r and \n.
To be clear: Read does not return the entered number, but the ASCII code of the character you entered, so you're using it wrong - what you need to do is convert the string the user enters to a number like so:
int number = Convert.ToInt32(Console.ReadLine());
You could also check for errors easily like this:
int number;
if (!Int32.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("What you entered is not a number!");
return;
}

The Console.Read reads only the next character. This is not what you want. What happens is this:
you type 7 => you read the character (ascii code) 0x37 for x
you press ENTER => you read 0x0A (\r) for n
etc...
you want to use Console.ReadLine() which terminates when you hit ENTER and returns a string that you can parse as int:
Console.Write("Insert x: ");
string input = Console.ReadLine();
int x = int.Parse(input);
You may want to add error handling if the user types "abc" instead of an int or use
int x;
if (!int.TryParse(input, out x))
Console.WriteLine("This was no number!");

You should use ReadLine and convert to int 32
Thes is the right code:
int y = 0;
Console.WriteLine("insert x");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("insert n");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("insert a");
int a = Convert.ToInt32(Console.ReadLine());
int sum = (2 * n - 1) * a;
int sum2 = (2 * n * a);
int sum3 = (2 * n + 1) * a;
if (x <= 0) y = 0;
else if (x > sum && x <= sum2) y = a;
else if (x > sum2 && x <= sum3 || n <= 3 || n >= 1) y = 0;
Console.WriteLine("Y = " + y);
Console.ReadLine();

Everyone has given a solution but the reason why
Your code doesn't work is this.
The
Console.Read
Returns the ASCII value of the keypressed.
It means saying something like
int i = Console.Read();
And hitting the 4key on your keyboard will store the value 53, which is the ASCII value of the 4key in variable i instead of ur intended integer "4".
To fully understand this check variable values by using breakpoints after Console.Read to see what is really stored in variable a, n and y.

Related

How can i make the user to give the right value?

The problem is that the courselist[y] works only for 0 value or 1 if i add a second courselist.How i can obligate the user to give the right value?
Also if the courselist is empty , what i have to do to show the appropiate message?
public static void AddTrainer()
{
Console.WriteLine("Trainer name");
string sname = Console.ReadLine();
Trainer tr = new Trainer(Helper.trainerlist.Count() + 1, sname);
Helper.trainerlist.Add(tr);
Console.WriteLine("Give course");
int y = Convert.ToInt32(Console.ReadLine());
//y = y - 1;
Helper.courselist[y].trainerIDlist.Add(Helper.trainerlist.Count());
Helper.ShowMenu2();
}
You could ask again until the user provides the correct value
string input;
do
{
Console.WriteLine("Give course (0 or 1)");
input = Console.ReadLine();
}
while (input != "0" && input != "1");
int y = Convert.ToInt32(input);
Console.WriteLine("Give course");
int y;
while (!int.TryParse(Console.ReadLine(), out y) || y >= Helper.courselist.Count() || y < 0)
{
Console.WriteLine("Give course that already created (1,2,3,...etc)");
}
Helper.courselist[y].trainerIDlist.Add(Helper.trainerlist.Count());
This worked , but i want to give 1 for the first courselist , not 0. And what if the courselist is empty?

count odd and even digits in a number

I try to write program that check the ratio between odd and even
digits in a given number. I've had some problems with this code:
static void Main(string[] args)
{
int countEven = 0 ;
int countOdd = 0 ;
Console.WriteLine("insert a number");
int num = int.Parse(Console.ReadLine());
int length = num.GetLength;
for (int i = 0;i<length ; i++)
{
if((num/10)%2) == 0)
int countEven++;
}
}
any ideas?
The problem is that int does not have a length, only the string representation of it has one.As an alternative to m.rogalski answer, you can treat the input as a string to get all the digits one by one. Once you have a digit, then parsing it to int and checking if it is even or odd is trivial.Would be something like this:
int countEven = 0;
int countOdd = 0;
Console.WriteLine("insert a number");
string inputString = Console.ReadLine();
for (int i = 0; i < inputString.Length; i++)
{
if ((int.Parse(inputString[i].ToString()) % 2) == 0)
countEven++;
else
countOdd++;
}
Linq approach
Console.WriteLine("insert a number");
string num = Console.ReadLine(); // check for valid number here?
int countEven = num.Select(x => x - '0').Count(x => x % 2 == 0);
int countOdd = num.Select(x => x - '0').Count(x => x % 2 != 0);
Let's assume your input is : 123456
Now all you have to do is to get the modulo from the division by ten : int m = num % 10;
After that just check if bool isEven = m % 2 == 0;
On the end you have to just divide your input number by 10 and repeat the whole process till the end of numbers.
int a = 123456, oddCounter = 0, evenCounter = 0;
do
{
int m = a % 10;
switch(m % 2)
{
case 0:
evenCounter++;
break;
default: // case 1:
oddCounter++;
break;
}
//bool isEven = m % 2 == 0;
}while( ( a /= 10 ) != 0 );
Online example
Made a small change to your code and it works perfectly
int countEven = 0;
int countOdd = 0;
Console.WriteLine( "insert a number" );
char[] nums = Console.ReadLine().ToCharArray();
for ( int i = 0; i < nums.Length; i++ )
{
if ( int.Parse( nums[i].ToString() ) % 2 == 0 )
{
countEven++;
}
else
{
countOdd++;
}
}
Console.WriteLine($"{countEven} even numbers \n{countOdd} odd numbers");
Console.ReadKey();
What I do is get each number as a a character in an array char[] and I loop through this array and check if its even or not.
If the Input number is a 32-bit integer (user pick the length of the number)
if asked:
The number of even digits in the input number
Product of odd digits in the input number
The sum of all digits of the input number
private void button1_Click(object sender, EventArgs e) {
int num = ConvertToInt32(textBox1.Text);
int len_num = textBox1.Text.Length;
int[] arn = new int[len_num];
int cEv = 0; pOd = 0; s = 0;
for (int i = len_num-1; i >= 0; i--) { // loop until integer length is got down to 1
arn[i] = broj % 10; //using the mod we put the last digit into a declared array
if (arn[i] % 2 == 0) { // then check, is current digit even or odd
cEv++; // count even digits
} else { // or odd
if (pOd == 0) pOd++; // avoid product with zero
pOd *= arn [i]; // and multiply odd digits
}
num /= 10; // we divide by 10 until it's length is get to 1(len_num-1)
s += arn [i]; // sum of all digits
}
// and at last showing it in labels...
label2.Text = "a) The even digits count is: " + Convert.ToString(cEv);
label3.Text = "b) The product of odd digits is: " + Convert.ToString(pOd);
label4.Text = "c) The sum of all digits in this number is: " + Convert.ToString(s);
}
All we need in the interface is the textbox for entering the number, the button for the tasks, and labels to show obtained results. Of course, we have the same result if we use a classic form for the for loop like for (int i = 0; and <= len_num-1; i++) - because the essence is to count the even or odd digits rather than the sequence of the digits entry into the array
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
});
// Continue with code
}
EDIT:
You could also do this with a helper (local) function within the method body:
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
// Alternative method:
IsEven(b) ? evenChars++ : oddChars++;
});
// Continue with code
bool IsEven(byte b) => b % 2 == 0;
}
Why am I using a byte?
Dealing with numbers, it is ideal to use datatypes that don't take up as much RAM.
Granted, not as much an issue nowadays with multiple 100s of gigabytes possible, however, it is something not to be neglected.
An integer takes up 32 bits (4 bytes) of RAM, whereas a byte takes up a single byte (8 bits).
Imagine you're processing 1 mio. single-digit numbers, and assigning them each to integers. You're using 4 MiB of RAM, whereas the byte would only use up 1 MiB for 1 mio. numbers.
And seeming as a single-digit number (as is used in this case) can only go up to 9 (0-9), you're wasting a potential of 28 bits of memory (2^28) - whereas a byte can only go up to 255 (0-255), you're only wasting a measly four bits (2^4) of memory.

Cumulative Binomial Probability C#

I'm trying to calculate the cumulative binomial probability of 'n' trials, with 'p' probability and 'r' as the successful outcome of each trial. I have written the following code that works sometimes, but not always:
Console.WriteLine ();
Console.WriteLine ("B~(n, p)");
incorrectN:
Console.WriteLine ("Enter value of 'n': ");
int n = Convert.ToInt32 (Console.ReadLine ());
if (n < 0) {
Console.WriteLine ("ERROR: 'n' must be greater than 0");
goto incorrectN;
}
incorrectP:
Console.WriteLine ();
Console.WriteLine ("Enter value of 'p': ");
double p = Convert.ToDouble (Console.ReadLine ());
if (p > 1) {
Console.WriteLine ();
Console.WriteLine ("ERROR: 'p' must be between 0 and 1");
goto incorrectP;
}
Console.WriteLine ();
incorrectS:
int r = GetR();
int k = r;
double binomTotal = 0;
for (int j = r + 1; j > 0; j--) {
int nCr = Factorial(n) / (Factorial(n - (r - k)) * Factorial(r - k));
binomTotal = binomTotal + nCr * Math.Pow(p, (r - k)) * Math.Pow(1 - p, (n - (r - k)));
k--;
}
Console.WriteLine();
Console.WriteLine(binomTotal);
P.S. I have written the GetR() and Factorial() functions elsewhere within the class, where GetR() asks the user for the value of 'r' and Factorial() is defined as follows:
public static int Factorial(int x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
I tested the code with values n = 10, p = 0.5 and r = 5 and the output is 0.623046875, which is correct. However, when I use n = 13, p = 0.35 and r = 7, I get 0.297403640622647 instead of 0.9538.
Any help would be much appreciated.
In addition to your own answer:
public static double Factorial(double x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
accepts a double parameter, which means that x is not restricted to be an integer.
So you could call your Factorial method like this.
var fac1 = Factorial(1.4);
var fac2 = Factorial(2.7);
However, this does not make sense since the factorial is defined only* for , meaning that
is undefined.
So, instead of using double and allowing for invalid inputs, you should be using long instead, which has a greater range than int.
public static long Factorial(long x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
* there are some cases where factorials can be used with real values as well - e.g. by using the gamma function - but I don't think they're relevant to your use case and therefore you should not allow invalid parameters.
Change:
public static int Factorial(int x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
To:
public static double Factorial(double x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
Because Factorial(13) is too large for Int32.

Do while problems when trying to loop if condition is not attain

I'm trying to have my program work by inputting an integer between 10-50 and if they didn't input within the acceptable range the loop will go back by making them input again. But I can't seem to understand why my program doesn't work. I know the logic behind but I think the codes is the problem. Here is my code
Console.WriteLine("Enter a digit between 10 and 50 ");
xx = Console.ReadLine();
x = int.Parse(xx);
do
{
if (x > 10 && x < 50)
Console.WriteLine("Pleae input again: ");
}
while (x <= 10 && x >= 50);
Console.WriteLine("The number is in between!");
Console.Read();
The if condition is wrong, and the while condition is wronger!
Try this instead:
Console.WriteLine("Enter a digit between 10 and 50 ");
do
{
xx = Console.ReadLine();
x = int.Parse(xx);
if (10 <= x && x <= 50)
break;
Console.WriteLine("Pleae input again: ");
}
while (true);
How about this:
string xx;
int x;
Console.WriteLine("Enter a digit between 10 and 50 ");
bool cont = true;
do
{
xx = Console.ReadLine();
if (int.TryParse(xx, out x) && 10 <= x && x <= 50)
cont = false;
else
Console.WriteLine("Pleae input again: ");
}
while (cont);
Seeing while(true) makes my skin crawl. And, you should always use int.TryParse instead of int.Parse for user input.
Check your IF and WHILE conditions.. Try this:
Console.WriteLine("Enter a digit between 10 and 50 ");
do
{
xx = Console.ReadLine();
x = int.Parse(xx);
if (x <= 10 || x >= 50)
Console.WriteLine("Pleae input again: ");
}
while (x <= 10 || x >= 50);
Console.WriteLine("The number is in between!");
Console.Read();
You need to ask for the input each time or you wont come out of the loop.
do
{
xx = Console.ReadLine();
x = int.Parse(xx);
if (x > 10 && x < 50)
Console.WriteLine("Pleae input again: ");
}
while (x <= 10 && x >= 50);
Console.WriteLine("The number is in between!");
Console.Read();

Solving Mathematical logics, placing digits in third number from digits of first and second number

I have two numbers.
First Number is 2875 &
Second Number is 852145
Now I need a program which create third number.
Third Number will be 2885725145
The logic is
First digit of third number is first digit of first number.
Second digit of third number is first digit of second number.
Third digit of third number is second digit of first number.
Fourth digit of third number is second digit of second number;
so on.
If any number has remaining digits then that should be appended at last.
I do not want to convert int to string.
int CreateThirdNumber(int firstNumber, int secondNumber)
{
}
So can anyone suggest me any solution to this problem?
I do not want to convert int to string.
Why?
Without converting to string
Use Modulus and Division operator.
With converting to string
Convert them to string. Use .Substring() to extract and append value in a string. Convert appended string to integer.
Here's a bit that will give you a lead:
Say you have the number 2875. First, you need to determine it's length, and then, extract the first digit
This can be easily calculated:
int iNumber = 2875;
int i = 10;
int iLength = 0;
while (iNumber % i <= iNumber){
iLength++;
i *= 10;
}
// iNumber is of length iLength, now get the first digit,
// using the fact that the division operator floors the result
int iDigit = iNumber / pow(10, iLength-1);
// Thats it!
First a little advice: if you use int in C#, then the value in your example (2885725145) is bigger than int.MaxValue; (so in this case you should use long instead of int).
Anyway here is the code for your example, without strings.
int i1 = 2875;
int i2 = 852145;
int i3 = 0;
int i1len = (int)Math.Log10(i1) + 1;
int i2len = (int)Math.Log10(i2) + 1;
i3 = Math.Max(i1, i2) % (int)Math.Pow(10, Math.Max(i1len, i2len) - Math.Min(i1len, i2len));
int difference = (i1len - i2len);
if (difference > 0)
i1 /= (int)Math.Pow(10, difference);
else
i2 /= (int)Math.Pow(10, -difference);
for (int i = 0; i < Math.Min(i1len, i2len); i++)
{
i3 += (i2 % 10) * (int)Math.Pow(10, Math.Max(i1len, i2len) - Math.Min(i1len, i2len) + i * 2);
i3 += (i1 % 10) * (int)Math.Pow(10, Math.Max(i1len, i2len) - Math.Min(i1len, i2len) + i * 2 + 1);
i1 /= 10;
i2 /= 10;
}
I don't understand why you don't want to use strings (is it homework?). Anyway this is another possible solution:
long CreateThirdNumber(long firstNumber, long secondNumber)
{
long firstN = firstNumber;
long secondN = secondNumber;
long len1 = (long)Math.Truncate(Math.Log10(firstNumber));
long len2 = (long)Math.Truncate(Math.Log10(secondNumber));
long maxLen = Math.Max(len1, len2);
long result = 0;
long curPow = len1 + len2 + 1;
for (int i = 0; i <= maxLen; i++)
{
if (len1 >= i)
{
long tenPwf = (long)Math.Pow(10, len1 - i);
long firstD = firstN / tenPwf;
firstN = firstN % tenPwf;
result = result + firstD * (long)Math.Pow(10, curPow--);
}
if (len2 >= i)
{
long tenPws = (long)Math.Pow(10, len2 - i);
long secondD = secondN / tenPws;
result = result + secondD * (long)Math.Pow(10, curPow--);
secondN = secondN % tenPws;
}
}
return result;
}
This solves it:
#include <stdio.h>
int main(void)
{
int first = 2875,second = 852145;
unsigned int third =0;
int deci,evenodd ,tmp ,f_dec,s_dec;
f_dec = s_dec =1;
while(first/f_dec != 0 || second/s_dec != 0) {
if(first/f_dec != 0) {
f_dec *=10;
}
if( second/s_dec != 0) {
s_dec *= 10;
}
}
s_dec /=10; f_dec/=10;
deci = s_dec*f_dec*10;
evenodd =0;tmp =0;
while(f_dec != 0 || s_dec !=0 ) {
if(evenodd%2 == 0 && f_dec !=0 ) {
tmp = (first/f_dec);
first -=(tmp*f_dec);
tmp*=deci;
third+=tmp;
f_dec/=10;
deci/=10;
}
if(evenodd%2 != 0 && s_dec != 0) {
tmp= (second/s_dec);
second -=(tmp*s_dec);
//printf("tmp:%d\n",tmp);
tmp*=deci;
third += tmp;
s_dec/=10;
deci/=10;
}
evenodd++;
}
printf("third:%u\ncorrct2885725145\n",third);
return 0;
}
output:
third:2885725145
corrct2885725145
#include <stdio.h>
long long int CreateThirdNumber(int firstNumber, int secondNumber){
char first[11],second[11],third[21];
char *p1=first, *p2=second, *p3=third;
long long int ret;
sprintf(first, "%d", firstNumber);
sprintf(second, "%d", secondNumber);
while(1){
if(*p1)
*p3++=*p1++;
if(*p2)
*p3++=*p2++;
if(*p1 == '\0' && *p2 == '\0')
break;
}
*p3='\0';
sscanf(third, "%lld", &ret);
return ret;
}
int main(){
int first = 2875;
int second = 852145;
long long int third;
third = CreateThirdNumber(first, second);
printf("%lld\n", third);
return 0;
}

Categories

Resources