简体   繁体   中英

Keeps crashing on 3rd if condition

So I am kind of new to programming (16 y/o) and I have been solving problems for a while now, but now I am solving this one prob (which is quite easy) there seems to be just one thing getting on my way. The problem is pretty simple, it only needs me to read 3 integers and print out the greatest one, I have already solved it in C++/C and had no problem, at all. But this one, It prints out and works perfectly when the first two if conditions are true (if a is the greatest value, it prints a, if b is the greatest value it prints b) but when c is the greatest value it comes out empty. Sorry for the long post, hope someone can help me out.

using System;

namespace MaxP351 { class MainClass { public static void Main (string[] args) { string[] input = Console.ReadLine ().Split (' '); // getting input as string int[] nums = new int[input.Length]; // declaring int array with same length as input for (int i = 0; i < input.Length; i++) { // starting a for loop to convert input string to int in nums[] nums[i] = Convert.ToInt32(input[i]); } int a, b, c; a = nums [0]; b = nums [1]; c = nums [2]; if (a > b && a > c) { Console.WriteLine (a); break; } else if (b > a && b > c) { Console.WriteLine (b); break; } else if (c > a && c > b) { Console.WriteLine (c); break; }

} }

If c is truly the largest number then your code should be printing out the value for c . If this were my code, I would set a break point at your if statement and see what the values are. Alternatively you can print out the values of a,b and c right before your if statements and make sure they are the values that you expect. Example:

Console.WriteLine("Values before if statement:")
Console.WriteLine (a);
Console.WriteLine (b);
Console.WriteLine (c);
if (a > b && a > c) {
...

Again - I would recommend going the breakpoint route, but the above might be a quick and dirty way to see the values if you aren't familiar with visual studio debugging.

In summary - your code should give you the desired output. The problem most likely lies somewhere else.

1. No need break; for if-else statements.

2. No need if statements at all to display the largest integer. You can do below.

 Console.WriteLine(nums.Max())

3. If you don't want to use Max function. Do a proper loop which is better than too many if conditions;

    int? maxVal = null; // ? means nullable int. Set null just to initialize

    for (int i = 0; i < nums.Length; i++)
    {
      int currentNum = nums[i];
      if (!maxVal.HasValue || currentNum > maxVal.Value)
      {
        maxVal = currentNum;
      }
    }

   Console.WriteLine(maxVal);

You dont need a 'break' as you are using if-else if. Below should help

if (a > b && a > c) {
    Console.WriteLine (a);
} else if (b > a && b > c) {
    Console.WriteLine (b);
} else {
    Console.WriteLine (c);
} 

Your if statements do not handle the numbers with same value

Correct as below:

if (a >= b && a >= c) {
    Console.WriteLine (a);
    //break;
} else if (b >= a && b >= c) {
    Console.WriteLine (b);
    //break;
} else {
    Console.WriteLine (c);
    //break;
} 

Try this

static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Input first number: ");
            var a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Input second number: ");
            var b = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Input third number: ");
            var c = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(a);
            Console.WriteLine(b);
            Console.WriteLine(c);
            if (a > b && a > c)
            {
                Console.WriteLine(a);
            }
            else if (b > a && b > c)
            {
                Console.WriteLine(b);
            }
            else if (c > a && c > b)
            {
                Console.WriteLine(c);
            }                
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }

Edit: If you make it dynamic then

static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Enter numbers (Example 25,46,19)");
            var input = Console.ReadLine();
            if (input == null)
            {
                Console.WriteLine("Your input is wrong");
                return;
            }
            var numbers = input.Split(',');
            //Sort by descending order
            for (int i = 0; i < numbers.Length; i++)
            {
                for (int j = 0; j < numbers.Length - 1; j++)
                {
                    if (Convert.ToInt32(numbers[i]) > Convert.ToInt32(numbers[j]))
                    {
                        var temp = Convert.ToInt32(numbers[i]);
                        numbers[i] = numbers[j];
                        numbers[j] = temp.ToString();
                    }
                }
            }
            Console.WriteLine("Greater Number is {0}", numbers[0]);                
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }

I executed your code it works properly if break is removed. there is no loop for the break statement to break and continue.it gives a compilation error. Remove that and it gives the correct result.

http://i.imgur.com/O02akZx.jpg here is the screen shot

Adding break; inside if/else blocks won't let your code compile :) After fixing this, your if/else code block in itself, looks correct. I tested it and it prints out c in my machine.

To answer your question related to If statements , if I were you, I would check:

  • If c is really the greatest (it may be greater than a, but not b, then it fails)
  • Unwanted space before or after c (maybe failing the conversion? You can try trimming string before conversion.)

This is neater if you can use .Max():

    public static void Main(string[] args)
    {
        string[] input = Console.ReadLine().Split(' '); // getting input as string            
        List<int> nums = new List<int>(); // declaring int array with same length as input
        for (int i = 0; i < input.Length; i++) // starting a for loop to convert input string to int in nums[]
        {                
            int intValue;
            if (Int32.TryParse(input[i].Trim(), out intValue))
            {
                nums.Add(intValue);
            }
        }

        int max = nums.Max();
        int min = nums.Min();

        Console.WriteLine("Largest: " + max);
        Console.WriteLine("Smallest: " + min);

        Console.WriteLine("Press Enter to exit.");
        Console.ReadLine();
    }

This is without .Max():

    public static void Main(string[] args)
    {
        string[] input = Console.ReadLine().Split(' '); // getting input as string            
        List<int> nums = new List<int>(); // declaring int array with same length as input
        for (int i = 0; i < input.Length; i++) // starting a for loop to convert input string to int in nums[]
        {                
            int intValue;
            if (Int32.TryParse(input[i].Trim(), out intValue))
            {
                nums.Add(intValue);
            }
        }

        //int max = nums.Max();
        //int min = nums.Min();

        int min = nums[0];
        int max = nums[0];
        for (int i = 0; i < nums.Count(); i++)
        {
            if (nums[i] < min) min = nums[i];
            if (nums[i] > max) max = nums[i];
        }

        Console.WriteLine("Largest: " + max);
        Console.WriteLine("Smallest: " + min);

        Console.WriteLine("Press Enter to exit.");
        Console.ReadLine();
    }

Note:

  • List<int> was used to accommodate user adding more than 3 values.

  • Avoided using a, b, c so that the program can accept more than 3 values.

  • Used Int32.TryParse(your_string, out outputInt) to conveniently detect parse errors and move on. Use .Trim() to remove spaces before and after each text block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM