C# >> Something with the numbers get scrambled up - c#

So this is what happens: I enter a number and what happens is that it writes out only 1 number: 324, like the variable c is getting this value for no reason..
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter a number with change");
double num = double.Parse(Console.ReadLine());
num = (int)num;
int c = 0;
Console.WriteLine(num);
while (num != 0)
{
num /= 10;
c++;
}
Console.WriteLine(c);
}
}

This program should loop infinitely if double could represent every real number. Say you enter in 1. Then the loop will divide it by 10, leaving 0.1. Since 0.1 is not equal to 0, the loop will continue, resulting in 0.01, etc.
double, however, only can support a minimum value of about 5E-324, so if you get a number that small and try to divide it by 10, you'll get zero.
So your program loops about 324 times, and quits after it gets a small enough number.

Try printing out num inside the loop. You'll see it tries to divide by 10 (division like this can never end in 0) infinitely until it can no longer hold that small of a value and == 0 will return true.
Just because you set num to it's rounded value by using (int)num doesn't mean it'll behave like an int it'll still end up as a fractional when dividing, use an int if you want it to be:
Console.WriteLine("enter a number with change");
double num = double.Parse(Console.ReadLine());
int num2 = (int)num;
int c = 0;
Console.WriteLine(num2);
while (num2 != 0)
{
num2 /= 10;
c++;
}
Console.WriteLine(c);

Related

Is there a nice way to limit C# console application memory consumption for displaying content? [duplicate]

Code:
This program checks if the 2 numbers entered and their sum are divisible by the numbers 2 - 9, and displays the remaining divisible numbers (excluding the one being reviewed).
static void Main(string[] args)
{
for (int i = 2; i < 10; i++)
{
Challenge(2, 6, i);
}
Console.ReadLine();
}
static void Challenge(int num1, int num2, int Divisor)
{
int sum = num1 + num2;
bool SumDivisible = sum % Divisor == 0;
bool num1Divisible = num1 % Divisor == 0;
bool num2Divisible = num2 % Divisor == 0;
int highNum = 80;
List<int> NumbersDivisible = Enumerable.Range(1, highNum).Where(x => x % Divisor == 0).ToList();
// Use the booleans to determine output.
if (SumDivisible || num1Divisible || num2Divisible)
{
if (SumDivisible)
{
Console.WriteLine("The SUM ({0}) is divisible by {1}! \nThe remaining USABLE numbers for {1} are:\n", sum, Divisor);
outputListExceptInt(NumbersDivisible, sum);
//output
Console.WriteLine("\n\n");
}
if (num1Divisible)
{
Console.WriteLine("The FIRST number ({0}) is divisible by {1}! \nThe remaining USABLE numbers for {1} are:\n", num1, Divisor);
outputListExceptInt(NumbersDivisible, num1);
//output
Console.WriteLine("\n\n");
}
if (num2Divisible)
{
Console.WriteLine("The SECOND number ({0}) is divisible by {1}! \nThe remaining USABLE numbers for {1} are:\n", num2, Divisor);
outputListExceptInt(NumbersDivisible, num2);
//output
Console.WriteLine("\n\n");
}
}
else
{
Console.WriteLine("The NUMBERS chosen and their SUM are not divisble by {0}. \nThe USABLE numbers for {0} are:\n", Divisor);
outputListExceptInt(NumbersDivisible);
Console.WriteLine("\n\n");
}
}
public static void outputListExceptInt(List<int> NumbersDivisibleByDivisor, int except = 0)
{
var Numbers = except > 0 ? NumbersDivisibleByDivisor.Where(x => x != except) : NumbersDivisibleByDivisor;
foreach (int num in Numbers)
{
Console.WriteLine(num);
}
}
Problem:
I'm finding that when I set the range (highNum) to anything over 89, a noticeable portion from the top of the window gets cut off:
highNum = 89:
highNum = 90:
Its cutting off 6 lines just with that small jump, and I'm not sure why.
Question:
My best guess is that there must be some limit on the output that can be displayed by the Console Window. Is this correct, or is something else causing this issue?
In a console window, click on Defaults
This opens a dialog box that allows you to set the scrollback buffer size (max number of lines to retain) by default in all of your console windows.
In my screenshot it is set to 9000 because I often log output to a console, and sometimes need to be able to scroll way back.
You can also modify it from your program for the console it is running in using Console.SetBufferSize().
Yes, the console has a width and height limit. And you can change it:
Answer modified from what's given here on microsoft's website:
Click the upper-left corner of the Command Prompt window, and then click Properties.
Click the Layout tab.
In Screen Buffer Size, type or select 2500 in Height.
Save the props by pressing OK.
You just have small buffer.

How do I create a C# program that asks for a value between 1 and 100 that uses a loop

so I am trying to create a C# program that asks for a value between 1 and 100 that uses a loop to determine the sum of all values between 1 and the entered value and if the number entered in is less than one or more than 100 it prints out "Sorry. Try again." I've been working on this for days but I can't get it to print the sum, I keep getting 0 and whenever I test it and enter a number under one or over 100, it won't print the error message I want. Here is the code:
using System;
namespace PrintSumL
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a beginning value between 1 and 100");
int s = Convert.ToInt32(Console.ReadLine());
int sum = 0;
Console.WriteLine("Sum of values: " + sum);
Console.ReadKey();
Random rand = new Random();
rand.Next(1, 51);
while (0 < s && s < 101)
{
sum += s;
s++;
if (s < 0 && 101 < s)
{
Console.WriteLine("Invalid input. Try again.");
}
{
}
{
}
}
}
}
}
You can think of the program as executing line by line from top to bottom, and only moving back up when it reaches the end of the while loop. The end of the while loop is the } that matches the { at the start of the loop.
Knowing that, you can see why it always says sum is zero. From your code:
int sum = 0;
Console.WriteLine("Sum of values: " + sum);
Since the program executes "line by line from top to bottom", it will first set sum to 0, and then print sum out. So it will always print "Sum of values: 0". If you want it to print out the sum after it has calculated it, then you need to move the WriteLine down below where the sum is calculated.
The same issue applies to the "Invalid input. Try again.": the line that prints this statement appears after while (0 < s && s < 101), so will only execute if s is between 0 and 101. Since you're trying to catch the scenario where s is not between 0 and 101, you'll need to move the statement to above the while loop.
So, to fix your immediate problems, just do two things:
1) move the two lines
Console.WriteLine("Sum of values: " + sum);
Console.ReadKey();
to after the while loop (just after the } which is at the same level of indentation as while).
2) move the three lines
if (s < 0 && 101 < s)
{
Console.WriteLine("Invalid input. Try again.");
}
up to just below int s = Convert.ToInt32(Console.ReadLine());, and then double check the logic. It sounds like you want to print the statement if s is less than zero or s is greater than 101.
if loops are a requirement you should follow Heath Raftery instruction
else you could write something like:
static void Main(string[] args)
{
Console.WriteLine("Enter a beginning value between 1 and 100");
int s = Convert.ToInt32(Console.ReadLine());
if (s < 0 || s > 100)
Console.WriteLine("Invalid input. Try again.");
else
Console.WriteLine($"Sum of values: {Enumerable.Range(1,s).Sum()}");
}
or as haldo commented you could just use the formula of N * (N+1) / 2 and replace the last WriteLine with:
Console.WriteLine($"Sum of values: {s * (s+1) / 2}")
Try this:
static void Main(string[] args)
{
while (true)
{
Console.Write("Enter a number between 1 and 100: ");
int Number = Convert.ToInt32(Console.ReadLine());
if (Number < 0 || Number > 100)
Console.WriteLine("Sorry. Try again.");
else
{
int sum = 0;
for (int i = 1; i <= Number; i++)
{
sum = sum + i;
}
Console.WriteLine("Sum of values: " + sum);
}
}
}
Here is an algorithm that works...
Console.WriteLine("Enter a value between 1 and 100");
var input = int.Parse(Console.ReadLine());
int sum = 0;
if (input<1 || input>100) {
Console.WriteLine("Sorry, Try again");
}
else{
while(input > 2){
input-=1;
sum+=input;
}
}
Console.WriteLine("Sum of values: " + sum);

How to divide number on separate digits to add values to each other

can you help me figure out how to calculate this way, for example I have some integer:
first I need condition
if (x < 10) to avoid asked calculation for single numbers
now if number contains more then 1 digit need to calculate it second way, for example, I got 134 how to separate it to calculate it this way 1 + 3 + 4 to attach this value 8 to variable.
So question is how to separate numbers
try
int num = 12345;
// holder temporarily holds the last digit of the number
int holder = 0;
int sum = 0;
while (num>0)
{
holder = num%10;
num = num/10;
sum += holder;
}
//sum would now hold the sum of each digit
This isn't C# in particular, but you can loop over your number then get it digit by digit.
// -- c
int num = 134;
int sum = 0;
while(num != 0) {
ones_digit = num % 10;
sum += ones_digit;
num = (num - ones_digit) / 10;
}
printf("sum: %d", sum);
On higher-level languages like javascript or python, accessing the digits can also be done by converting the integer to a string, then casting each char to an int type.
// -- javascript
var num = 134;
var digits = num.toString().split("").map(parseInt);
console.log(digits);

add digits of each double digit numner

Here is my code. I want to have users enter any number of doubles continuously until 100 times (could be however number of times the user wants but less than 100). Display sum of all values entered. In my code, I don't know how to allow users to enter numbers continuously (im guessing you would have a while loop).
Thanks a lot!
Console.WriteLine("Enter double");
double.first = double.Parse(Console.ReadLine());
while(first != 0)
{
Console.WriteLine("Enter double");
int num = int.Parse(Console.ReadLine());
double sum;
while(num != 0)
{
double ten = num/10;
double tenth = Math.Floor(ten);
double oneth = num % 10;
sum = tenth + oneth;
Console.WriteLine("{0}", sum);
break;
}
first = double.Parse(Console.ReadLine());
}
I want to have users enter any number of doubles continuously until
100 times (could be however number of times the user wants but less
than 100).
You need to keep track of 3 things.
The next double.
The running total.
How many times the user has provided input.
Variables:
double next;
double runningTotal = 0;
int iterations = 0;
Now, to continuously receive input from the user, you can write a while-loop as you correctly identified. In this loop you should check for two things:
That the next value is a double and that it is not 0.
That the user has not provided input more than 100 times.
While-loop:
while (double.TryParse(Console.ReadLine(), out next) && next != 0 && iterations < 100) {
// Count number of inputs.
iterations++;
// Add to the running total.
runningTotal += next;
}
Display sum of all values entered.
Simply write to the console.
Output:
Console.WriteLine("You entered {0} number(s) giving a total value of {1}", iterations+1, runningTotal);
Complete example:
static void Main()
{
double runningTotal = 0;
double next;
var iterations = 0;
Console.Write("Enter double: ");
while (double.TryParse(Console.ReadLine(), out next) && next != 0 && iterations < 100)
{
runningTotal += next;
iterations++;
Console.Write("Enter double: ");
}
Console.WriteLine("You entered {0} number(s) giving a total value of {1}", iterations+1, runningTotal);
Console.Read();
}
Edited after comment:
Ok, I'm still assuming this is homework, but here are the basics...
I would do this in two phases, data input, then calcualtion.
Create something to store the input in and a counter for the loop
var inputs = new List<double>();
var counter = 0;
Now comes you while loop for your inputs...
while(counter < 100)
{
var tempInput = 0.0D;
Double.TryParse(Console.ReadLine(), out tempInput);
if(tempInput == 0.0D)
{
// The user did not enter something that can be parsed into a double
// If you'd like to use that as the signal that the user is finished entering data,
// just do a break here to exit the loop early
break;
}
inputs.Add(tempInput);
// This is your limiter, once counter reaches 100 the loop will exit on its own
counter++;
}
Now you can just perform the calcualtions on the values you've accumulated...
var total = 0.0D;
foreach(var value in inputs)
{
total += value;
}
Now display the value in total.
Keep in mind there are a multitude of ways to do this this one is just an example to get you past the problem of aquiring the data.

how do I print a number less than 1 but greater than 0?

I am expressing the power method in a script, at one point I am trying to do a negative, which is 1 / final_answer
the thing is it does not print things such as 2^-3 which is .125
using System;
class MainClass
{
static void Main()
{
Console.Write ("Enter a base number: ");
string str_x = Console.ReadLine ();
double x = double.Parse (str_x);
Console.Write ("Enter an exponent: ");
string str_n = Console.ReadLine ();
double n = double.Parse (str_n);
double final = 1;
int count = 1;
while (count != n+1) {
final = final * x;
count++;
}
if (n < 0)
final = 1 / final;
Console.WriteLine(final);
}
}
First of all, the loop
int count = 1;
while (count != n + 1)
final = final * x;
count++;
}
cannot end if n == -3 since count is always positive.
In addition, it could be an endless loop because you compare int and double
double n = float.Parse (str_n);
....
int count = 1;
while (count != n + 1) {
You should avoid use of == and != with doubles.
With negative values of the exponent, your loop never terminates because count will never reach a negative value (or zero), at least until it overflows.
And as others said, read the exponent as an integer, not a double.

Categories