Why is my C# prime number calculator not working? [closed] - c#

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 2 years ago.
Improve this question
It is my code:
using System;
namespace ConsolePrimeNumberCalculator1
{
class Program
{
static void Main(string[] args)
{
Console.Title = "ConsolePrimeNumberCalculator1";
string input = Console.ReadLine();
int a, b, c, d, e = 0;
if (int.TryParse(input, out a))
{
if (a > 1)
{
for (b = 2; b <= a; b++)
{
d = 2;
c = 1;
while (d < b)
{
if (b % d == 0)
{
c = 0;
break;
}
d++;
}
if (c == 1)
{
e = 1 + e;
}
if (a > 50000)
{
Console.WriteLine("Number is Big");
break;
}
}
if (a < 50001)
{
Console.WriteLine(e);
}
}
else
{
Console.WriteLine("Number is Small");
}
}
else
{
Console.WriteLine("Number is not Integer");
}
if (a < 1)
{
if (!int.TryParse(input, out a))
{
Console.WriteLine("Number is Small");
}
}
Console.ReadKey();
}
}
}
My problem:
I wrote 2.3. But my application wrote this:
"Number is not integer" and "Number is Small"
"Number is not integer" is a true sentence. But I think "Number is Small" is a false sentence. Because 2.3 is not smaller than 1. Why does my application wrote "Number is Small"? Is it C# bug?

This is because your TryParse calls cannot parse it to an integer (this is why they are returning false).
This line:
int.TryParse(input, out a)
Will return false and a will be 0.
So when you hit your final if:
if (a < 1)
{
if (!int.TryParse(input, out a))
{
Console.WriteLine("Number is Small");
}
}
a is zero to start, it still can't parse it, so a remains zero and you hit this write.

int.TryParse("2.3", out a); will try to parse "2.3" as an integer, and if it succeeds, it will assign it's value to a (currently 0).
As TryParse fails (cannot convert "2.3" to int), it never assigns the value to a, which remains 0, hence the code falls in the else block.

int a = 0 stills 0 after parsing because the parse function fails... Try to debug and see it yourself

Actually you have int a = 0 than
(!int.TryParse(input, out a)) fails and
a is less than 1 that's why it is printing "Number is Small"

Related

While loop not executing C# [closed]

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 6 months ago.
Improve this question
using System;
using System.Data;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
bool calc1 = false;
bool end = false;
double answer = 0.0;
double num1 = Convert.ToDouble(Console.ReadLine());
string op1 = Console.ReadLine();
double num2 = Convert.ToDouble(Console.ReadLine());
if (op1 == "*") ;
{
answer = (num1 * num2);
calc1 = true;
}
if (op1 == "/") ;
{
answer = (num1 / num2);
calc1 = true;
}
if (op1 == "+") ;
{
answer = (num1 + num2);
calc1 = true;
}
if (op1 == "-") ;
{
answer = (num1 - num2);
calc1 = true;
}
while (end == false) ;
{
string op2 = Console.ReadLine();
if (op2 == "*") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer * num3);
}
if (op2 == "/") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer / num3);
}
if (op2 == "+") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer + num3);
}
if (op2 == "-") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer - num3);
}
if (op2 == "=") ;
{
Console.WriteLine(answer);
end = true;
}
}
}
}
}
I am trying to create a multi integer calculator but for some reason, my while loop does not execute so once I enter the first 2 digits and operator, it stops running. Before hand, I had 2 while loops and it would run the second one but it would not print the answer variable when the user entered =.
your issue is the semicolon ; after the while condition.
Remove it. (and also all the ; after the if conditions!)
Currently the code is like that:
while (condition);
{ you big block of code } // <--- this is not part of the while loop
Because of the semicolon, it's actually the same as
while (condition)
;
the big block of code // <--- this is not part of the while loop
or even:
while (condition)
{
}
the big block of code // <--- this is not part of the while loop
If you remove the semicolon, then the block is now part of the loop;
while (condition)
{
the big block of code // <--- Now it's like you intended to write!
}
This is the same problem with the ifs, by the way.
If you write a if (condition);, that's like if (condition) { }, and the other block below will be always executed.
You put a semicolon after the while loop, nothing is inside of it.
If you want to have a forever loop, I suggest you use while(true)
Edit:
OP, If you wanted to exit the loop at any time, you could simply just do break; instead of setting the condition equal to false.

I can't get any output and my statements don't execute properly because of this, however, every if statement does execute even when it shouldn't? [closed]

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 2 years ago.
Improve this question
I want to write a program that multiples four numbers and outputs their sign whether if the answer is a negative or a positive number. I had to write the program using a logical operator but the thing is that I wanted to try first using a simple if statement series while also using relational operators. I wrote this code, and checked it multiple times, the code compiles and executes but shows no output. It says "The answer is " followed by a blank space and shows all 3 of my if statements. Can someone please kindly fix my code for me (and possibly tell me how to write such a program using logical operators where I give 4 inputs and I get the output saying if the answer after multiplying the 4 numbers is positive or negative, and if is there any way to do that without actually calculating aka multiplying) and tell me what exactly is wrong with my code. The code is given here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program746
{
class Program
{
static void Main(string[] args)
{
int a, b, c, d;
Console.WriteLine("Please enter the first number:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the second number:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the third number:");
c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the fourth number:");
d = Convert.ToInt32(Console.ReadLine());
int e = a * b * c * d;
if (e < 0) ;
{
Console.WriteLine("The result is negative and has the '-' sign ");
}
if (e > 0) ;
{
Console.WriteLine("The result is positive and has the'+' sign");
}
if (e == 0) ;
{
Console.WriteLine("The result is zero, and does not have a sign");
}
Console.WriteLine("The answer is ", e);
Console.ReadKey();
}
}
}
static void Main(string[] args)
{
int a, b, c, d;
Console.WriteLine("Please enter the first number:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the second number:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the third number:");
c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the fourth number:");
d = Convert.ToInt32(Console.ReadLine());
int e = a * b * c * d;
if (e < 0)
{
Console.WriteLine("The result is negative and has the '-' sign ");
}
if (e > 0)
{
Console.WriteLine("The result is positive and has the'+' sign");
}
if (e == 0)
{
Console.WriteLine("The result is zero, and does not have a sign");
}
Console.WriteLine("The answer is {0}", e);
Console.ReadKey();
}
Delete the semicolon after each if statement. Because with a semicolon at the end you terminate the if.
You can check out this link: https://social.msdn.microsoft.com/Forums/en-US/3508c3a2-fd1c-49db-93ea-f7bb5c2d27f4/extra-semicolon-suberst-conditional-flow?forum=csharpgeneral
Your if:
if (e < 0) ;
{
...
}
Correct if:
if (e < 0)
{
...
}
Instead of using four ReadLines, you could do a for loop with i = 4 and multiply each number to a result int or save them in a int array.
I would write the program like this:
static void Main(string[] args)
{
int result = PrintSign(4);
Console.WriteLine(string.Format("The answer is {0}", result));
Console.ReadLine();
}
private static int PrintSign(int maxNumbers)
{
int result = 0;
for (int i = 0; i < maxNumbers; i++)
{
int number = 0;
while (true)
{
Console.WriteLine(string.Format("Please enter number {0}:", i));
if (int.TryParse(Console.ReadLine(), out number))
break;
}
// if one number is zero, return 0 (multiply with zero and it's zero all the time)
if (number == 0)
return 0;
result *= number;
}
// check for negative number
if (result < 0)
Console.WriteLine("The result is negative and has the '-' sign");
// else, because zero is not possible at this point
else
Console.WriteLine("The result is positive and has the'+' sign");
return result;
}
Please like and accept the answer if this answered your question :)

Random number guessing game not working C# [closed]

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
I am trying to get this random number guessing game working. The program runs, but it doesn't give the "you won" message when you enter the correct number, and the hint feature does not give the feed back it is supposed to. Any help appreciated.
using System;
namespace randomNumberGame
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
var val = r.Next(1, 100);
var guess = 0;
bool correct = false;
var attemptsLeft = 5;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (!correct && attemptsLeft >= 1)
{
Console.Write("You have " + attemptsLeft + " lives left. Please enter your Guess: ");
string input = Console.ReadLine();
var message = "";
var difference = val - guess;
if (!int.TryParse(input, out guess))
{
Console.WriteLine("That's not a number.");
continue;
}
if (difference == 0)
{
Console.WriteLine("You have won");
correct = true;
}
else
{
if (Math.Abs(difference) >= 50)
{
message = Math.Sign(difference) == -1 ? "Very High" : "Very Low";
}
else if (Math.Abs(difference) < 50 && Math.Abs(difference) >= 20)
{
message = Math.Sign(difference) == -1 ? "High" : "Low";
}
else if (Math.Abs(difference) < 20 && Math.Abs(difference) >= 10)
{
message = Math.Sign(difference) == -1 ? "Moderatley High" : "Moderately Low";
}
else if (Math.Abs(difference) < 10)
{
message = Math.Sign(difference) == -1 ? "Somewhat High" : "Somewhat Low";
}
else Console.WriteLine("???");
}
attemptsLeft--;
}
}
}
}
"it doesn't give the you won message when you enter the correct number"
Actually, it does! But then the program exits so quickly that you never see it. To solve this, add a line that waits for the user to press a key at the end of your Main method, so you can see the final result:
// Add this as the last line of the main method:
Console.ReadKey();
"the hint feature does not give the feed back it is supposed too"
This is because you never output the hint message! At the end of your while loop, add a line to do so:
// Add this as the last line of the while loop:
Console.WriteLine(message);
These things can be found easily if you simply set a breakpoint in your code (in Vistal Studio, click the left margin next to one of the lines and a red dot will appear (or press F9)). Then you can step through the code using F10 and you can watch the values of local variables change and see what is happening step-by-step.
Another way to help avoid problems (and to narrow down where they occur) is to take out chunks of code that does something specific and put it in a method. This will make it easier to debug in the long run.
For example, we can write methods that take in a string to display to the user as a prompt for input, and return a strongly-typed value based on their entry. We can also have these methods take in an optional validation method that can be used to validate that the input they entered falls within a valid range (like a number from 1 to 100, or a name that's not longer than 25 characters):
public static string GetStringFromUser(string prompt,
Func<string, bool> validator = null)
{
string result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
result = Console.ReadLine();
} while (!(validator?.Invoke(result) ?? true));
return result;
}
public static int GetIntFromUser(string prompt,
Func<int, bool> validator = null)
{
int result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
!(validator?.Invoke(result) ?? true));
return result;
}
private static void ClearSpecificLineAndWrite(int cursorTop,
string message)
{
Console.SetCursorPosition(0, cursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, cursorTop);
Console.Write(message);
}
We can also write a helper method to get our "difference string", which could take in the guess, the number, and the min and max values, then calculate a percentage of how close they were and then return the appropriate string:
public static string GetDifferenceString(int guess, int number,
int minVal, int maxVal)
{
var percentAway =
Math.Abs(guess - number) / (double)(maxVal - minVal) * 100;
var direction = guess - number > 0 ? "High" : "Low";
if (percentAway < 10) return $"Very close, but {direction}";
if (percentAway < 20) return $"Just a little {direction}";
if (percentAway < 30) return $"Somewhat {direction}";
if (percentAway < 40) return $"Moderately {direction}";
if (percentAway < 50) return $"{direction}";
return $"Very {direction}";
}
This simplifies our main code by removing the loops and checking results from there, and lets us focus on our main tasks:
static void Main(string[] args)
{
var randomNumber = new Random().Next(1, 101);
var maxAttempts = 5;
var guess = 0;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
Console.WriteLine($"You have {maxAttempts - attempt} " +
$"out of {maxAttempts} attempts remaining.");
guess = GetIntFromUser("Please enter your guess (1 - 100): ",
i => i > 0 && i < 101);
if (guess == randomNumber)
{
Console.WriteLine($"You have won in {attempt + 1} tries!");
break;
}
Console.WriteLine(GetDifferenceString(guess, randomNumber, 1, 100));
}
if (guess != randomNumber)
{
Console.WriteLine("Sorry, you lose! The number was: " +
$"{randomNumber}");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}

For Loop Will Not Execute C# [closed]

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 6 years ago.
Improve this question
I am making a program that will a number of dice a number of times. I have made a method called 'RollDice'. the method works until the for loop. It returns to the main method after I type 'roll' in the console and i don't know why it won't execute the script in side the for loop. I have marked place where the code stops working. any help would be much appreciated, thanks!
using System;
using System.Collections.Generic;
namespace Dice Roller
{
class Program
{
public static void Main(string[] args)
{
int nos = 6;
int nod = 1;
int nor = 1;
string OP;
int x = 1;
while (x == 1)
{
Console.WriteLine("Random Dice Macine");
Console.WriteLine("Type 'edit' To Edit Dice Settings");
Console.WriteLine("Type 'clear' To Clear The Screan");
Console.WriteLine("Type 'exit' To Close The Aplication");
Console.WriteLine("Type 'roll' to Roll The Dice");
Console.Write("-> ");
OP = Console.ReadLine();
if (OP == "exit")
{
Environment.Exit(0);
}
else if (OP == "edit")
{
Console.Clear();
Console.WriteLine("Number Of Sides On The Dice");
Console.Write("->");
nos = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number Of Dice");
Console.Write("->");
nod = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number Of Roles");
Console.Write("->");
nor = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Setup Compleat! Press Space To Continue.");
Console.ReadKey();
Console.Clear();
}
else if (OP == "clear")
{
Console.Clear();
}
else if (OP == "roll")
{
RollDice(nor, nos, nod);
}
}
}
public static void RollDice(int nor, int nos, int nod)
{ //Code Works Here
Random gen = new Random();
List<int> numbers = new List<int>();
for (int n = 1; n < nod; n++)
{
for (int i = 1; i < nor; i++)
{ //But Not Here
numbers.Add(gen.Next(1, nos));
}
foreach (int element in numbers)
{
Console.Write(element + ", ");
}
numbers.Clear();
}
}
}
}
In for-loops the counter should start from 0 and not from 1. In your case nor and nod are equal to 1. That is why the loops are never executed.
Only thing I can see is that if nod or nor is 1 when the program reaches the for loops, the condition to end the loop is already met. Use '<=' instead in the ebd condition.
On line
for (int n = 1; n < nod; n++)
nod is 1, and n < nod check is termination for loop.
Either set i = 0 or set check n <= nod.

C# for loop error > is invalid [closed]

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 7 years ago.
Improve this question
I am trying to make a prime number generator.
I get three errors:
<21,22> expected >
<21,23> expression > is invalid
<21,24> expected ;
translated errors from norwegian. they may not be exact
using System;
namespace Primtall
{
class Program
{
static void Main(string[] args)
{
Generator G = new Generator();
G.gen();
}
}
public class Generator
{
int a = 0;
int divident = 0;
public void gen()
{
for (a; a<100; a++;)
{
for (divident; divident <= 50;divident++)
{
int div = a/divident;
if((div % 1) == 0)
{
Console.WriteLine(a);
}
else
{
break;
}
}
}
}
}
}
There is no need to define a and divident variables as fields. You make no use of them except in the loop. In fact, using class members (fields) as loop variables will immediately render your class as "not thread safe", becuase if two seperate threads execute the gen() method on the same Generator instance they will both fail to get correct results
Change your Generator class like this: (divident starting from 1 to avoid divide by zero exception)
public class Generator
{
public void gen()
{
for (int a = 0; a < 100; a++)
{
for (int divident = 1; divident <= 50; divident++)
{
int div = a / divident;
if ((div % 1) == 0)
{
Console.WriteLine(a);
}
else
{
break;
}
}
}
}
}
You declare variables before loops, so you must leave empty first argument in for:
for (; a < 100; a++)
{
for (; divident <= 50; divident++)
{
Or better declare loop variables in loop:
for (var a = 0; a < 100; a++)
{
for (var divident = 2; divident <= a / 2; divident++)
{
Also, you have some problems in algorithm:
int div = a/divident;
if((div % 1) == 0)
Should be replaced with:
if((a % divident) == 0)
{
flag = false;
break;
}
Declare flag in first loop as true and check it after second loop finish. If it's stil true - number is prime. Also, start second loop with 2 and end with a / 2
You seem to be misunderstanding how for loops work
for(Initialise; While; Action)
so in english what you are asking it to do is
for
a where a starts at 0
while a less than 100
perform body
then increment a by 1
this in code is
For(int a = 0;a<100;a++)
{
//body
}

Categories