Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I wrote a short code in c#, and it's function is like this:
First you choose how many times you want to put in a number, then you pick a number to sum
static void number()
{
Console.WriteLine("how many numbers, max is 999");
int n = int.Parse(Console.ReadLine());
if (n > 999)
{
return;
}
Console.WriteLine("enter number here:");
int d = int.Parse(Console.ReadLine());
if (d < -99999 || d > 99999)
{
return;
}
Console.WriteLine(n + " " + d + "which number has to be counted up");
for (int i = 0; i < n; i++)
{
int e = int.Parse(Console.ReadLine());
int c;
c = e + d;
Console.WriteLine(e + " " + c);
Console.WriteLine("press enter to input a new number");
Console.ReadKey();
i++;
}
}
If I put positive numbers, it works correctly. But if I put in negative numbers, It asks "enter number here" and after I put in a number, it shows the which number to count up writeline very quickly and then the application stops for no reason.
Any thoughts why this happens?
If you put a negative number into n, then i will never be less than n in your for loop (which you've set to run while i < n). This means the the for loop will never run and the as this is the last bit of code in you application, the program will end.
Here's what I get:
how many numbers, max is 999
-2
enter number here:
3
-2 3which number has to be counted up
When I enter the -2 it gets stored in the variable n. Later, in the for loop, the variable i starts out at zero, which means the i < n, so the loop quits without executing anything in the loop body.
Related
This question already has answers here:
int.Parse, Input string was not in a correct format
(7 answers)
Closed 2 years ago.
Here is my code :
using System;
namespace CappedSum
{
class Program
{
static void Main(string[] args)
{
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = 0;
while (sum<sumLimit)
{
int number = Convert.ToInt32(Console.ReadLine());
if (sum + number < sumLimit)
{
sum += number;
count++;
}
else if (sum + number > sumLimit)
{
Console.WriteLine(sum + " " + count);
}
}
}
}
}
I had to write a console application that reads from the keyboard a list of numbers until their sum reaches a certain limit also entered by the user.
The limit is given on the first line, and on the next lines will be the list of numbers which has to be added. The program will stop reading when the sum of the numbers entered so far exceeds the limit and will display the last amount that did not exceed the limit, as well as how many numbers were needed to calculate it.
for example : if I enter 10 (which is the limit) then I enter 2,3,2,6. The result will be 7 (which is the last amount that did not exceed the limit) and 3 (which represents how many numbers needed to calculate it).
Try out Int32.Parse instead of Convert.ToInt32. Also, a really basic I use sometimes to debug my same mistakes, is to write MessageBoxes after specific instructions, so if they do not work I never get to the message, viceversa if the message shows I know that works. I'd put two Messageboxes after the Int32.Parse(Console.Readline()) being like MessageBox.Show(sumlimit/number.ToString());. This way you know how far the code works.
There was a test in school where we had to write a C# console program that reads positive integers below 100 from user input and then writes out some details like the biggest number. I used a list to store the numbers. I tested it with some random numbers I typed in but the program only adds the numbers to list starting with the second smallest one.
int count = 0;
List<int> bekertek = new List<int>();
int bekert = Convert.ToInt32(Console.ReadLine());
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
/* This section is only for checking the list's elements
foreach (var i in bekertek)
{
Console.Write(i + " ");
}*/
Console.WriteLine("A bevitt adatok száma: {0}", count);
bekertek.Sort();
bekertek.Remove(bekertek.Last());
atlag = bekertek.Average();
Console.WriteLine("A legnagyobb érték: {0}", bekertek.Last());
Console.WriteLine("A legkisebb érték: {0}", bekertek.First());
Console.WriteLine("Az adatok átlaga: {0}", atlag);
What did I do wrong?
For input in console, I think the do...while loop is the ideal construct. Menus or requesting a number - it covers all of those.
As for what went wrong: Actually it adds all numbers to the collection (that debug code should confirm it). You just remove the smalest number from the collection between Sorting and Display:
bekertek.Sort();
bekertek.Remove(bekertek.Last()); //Should not have done this.
atlag = bekertek.Average();
There is a saying: "The 2 most common issues in Progamming is naming variables, chache invalidation and off-by-one errors." But this specific to make is somewhat unique :)
Edit: As Biesi Grr pointed out, you also ignore the first input:
int bekert = Convert.ToInt32(Console.ReadLine()); //this is never processed
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
Maybe you wanted to use a ReadKey() here? There is also no need for a counter - that is actually the job of List.Lenght. In any case, a do..while would make that line unessesary any way.
let us make a fixed, do...while version
bool repeat= true;
do{
int bekert = Convert.ToInt32(Console.ReadLine());
if(bekert > 0 && bekert < 100)
bekertek.Add(bekert);
else
repeat = false;
}while(repeat )
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
So I am doing an online coding challenge and have come across this issue that has me stumped:
This is my code:
static void Main(String[] args)
{
int noOfRows = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < noOfRows; i++)
{
string odds = "";
string evens = "";
//get the input word from console
string word = Console.ReadLine();
for (int j = 0; j < word.Length; j++)
{
//if the string's current char is even-indexed...
if (word[j] % 2 == 0)
{
evens += word[j];
}
//if the string's current char is odd-indexed...
else if (word[j] % 2 != 0)
{
odds += word[j];
}
}
//print a line with the evens + odds
Console.WriteLine(evens + " " + odds);
}
}
Essentially, the question wants me to get the string from the console line and print the even-indexed characters (starting from index=0) on the left, followed by a space, and then the odd-indexed characters.
So when I try the word 'Hacker', I should see the line printed as "Hce akr". When I debugged it, I saw the code successfully put the letter 'H' on the left (because it is index=0, thus even), and put the letter 'a' on the right (odd index). But then when it got to the letter 'c', instead of going through the first IF path (even index), it skips it and goes to the odd index path, and places it on the right hand side?
The funny thing is when I try the word 'Rank' it works fine and prints the correct statement: "Ra nk", yet other words do not.
Its just bizarre that I'm getting different results.
What am I missing?
word[j] is a character in your string; j is the index you want to check the evenness of.
if (j%2) should provide the correct path. You're using if( word[j] %2) which is doing modular arithmetic on a character, not an index. Most likely using modulo on the ASCII value. Hope this helps.
you want to check if the index is even,yet you compare word[j] % 2 == 0 which is not an index.
what you should do:
if(j % 2 == 0){
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm studying C# programming.
Nevertheless, I don't know how to solve these problems.
Like (Write a MyAvg method that gets 3 different double inputs and calculates the average of them. It should return the average as the output. Use the function in one simple program)
using System;
/*4. Write a MyAvg method that gets 3 different double inputs and calculates the average of them. It should return the average as the output. Use the function in one simple program*/
namespace ConsoleApp36
{
class Program
{
static void Main(string[] args)
{
double a, b, c;
double avg = 0;
Console.Write("Input the first value : ");
a = Convert.ToDouble(Console.ReadLine());
Console.Write("Input the second value : ");
b = Convert.ToDouble(Console.ReadLine());
Console.Write("Input the third value : ");
c = Convert.ToDouble(Console.ReadLine());
avg = (a + b + c) / 3;
Console.WriteLine("Average of 3 different values is : {0}", avg);
}
}
}
and
(Write a MyFact function that gets one integer as an input and calculates the factorial of it. It returns factorial as the result of the function. Use the function in one simple program. Use the function in one simple program.)
using System;
/*4. Write a MyAvg method that gets 3 different double inputs and calculates the average of them. It should return the average as the output. Use the function in one simple program*/
namespace ConsoleApp39
{
class Program
{
static void Main(string[] args)
{
int i, f = 1, num;
Console.Write("Input the number : ");
num = Convert.ToInt32(Console.ReadLine());
for (i = 1; i <= num; i++)
f = f * i;
Console.Write("The Factorial of {0} is: {1}\n", num, f);
}
}
}
Can you guys help me?
You should be more clear with your questions and show us that you actually tried to write some code. Anyways, here MyAvg and MyFact is just abbreviations for "MyAvarage" and "MyFactorial".
As you should know, average avarage in mathematics is simply summing n numbers, and then dividing the sum with n. So you should implement it in your function MyAvg. Here is how you should take the avarage of three double numbers;
double average = (a + b + c) / 3;
Also, for the function MyFact, you should be taking an int parameter, and then simply be implying the factorial algorithm. Let's assume you've sent 5 as a parameter to MyFact(), then you should be multiplying the number 5 decreasingly in a for loop, such as 5*4*3*2*1, and it will give you the result. You can return this result, or simply print it directly in function.
For loop to calculate factorials
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am very new to c# and I don't get it very quickly. If you can explain how and why like your talking to a 3yr old that would be great!!!
how do you make (enter the amount (-1 to stop)) repeat and end up with a total of all amounts entered?
Luckily, my 3-year old is sitting right here, so I had him write it out :)
var total = 0; // This will hold the sum of all entries
var result = 0; // This will hold the current entry
// This condition will loop until the user enters -1
while (result != -1)
{
// Write the prompt out to the console window
Console.Write("Enter the amount (-1 to stop): ");
// Capture the user input (which is a string)
var input = Console.ReadLine();
// Try to parse the input into an integer (if TryParse succeeds,
// then 'result' will contain the integer they entered)
if (int.TryParse(input, out result))
{
// If the user didn't enter -1, add the result to the total
if (result != -1) total += result;
}
else
{
// If we get in here, then TryParse failed, so let the user know.
Console.WriteLine("{0} is not a valid amount.", input);
}
}
// If we get here, it means the user entered -1 and we exited the while loop
Console.WriteLine("The total of your entries is: {0}", total);
We are calling it loops, little boy :P
UPDATE I dont know if i understood you, but now the code writes sum each time, and if you enter for example -5 it will be sum = sum - 5
class Program
{
static void Main(string[] args)
{
// thoose are variables, and they are storing data
int input = 0; // input integer number
int sum = 0; // sum of all numbers
while (true) //Infinite loop (executes undereneath code until true=true)
{
input = int.Parse(Console.ReadLine()); // read the line from user, parse to int, save to input variable
if (input == -1) break; // if integer input is -1, it stops looping (the loop breaks) and GOES (two lines down)
sum = sum+ input; // summing all input (short version -> s+=input)
Console.WriteLine("Actual Sum: "+sum); // HERE IS THE UPDATE
}
//HERE
Console.WriteLine("Your final sum is: " + s);
}
}