用户输入数组的大小,数组中的数字并搜索数组中的数字

时间:2015-12-16 07:52:19

标签: c# arrays

我正在自己学习C#,我需要一些帮助。我想创建一个控制台程序,用户输入的数字是浮点数数组的大小。然后程序将提示用户搜索(浮点)数字并告诉用户数组中是否存在该数字。

我遇到的问题是它不接受浮点数(到目前为止只有整数工作)并且它只会找到输入的第一个数字。

以下是我到目前为止编写的代码:

    public static void Main()
    {
        int size;
        int i;

        size = readNumber("How many numbers do you want to enter: ");
        float[] numbers = new float[size];

        for (i = 0; i < size; i++)
            numbers[i] = readFloat("Enter a number: ");
        Console.WriteLine();


        Console.WriteLine("Please enter any number to check if it exists in the array: ");
        float userInput = float.Parse(Console.ReadLine());
        for (i = 0; i < size; i++)
        {
            if (userInput == numbers[i])
            {
                Console.Write("Congratulations! The number you entered exists in the array.");
                break;
            }
            else
            {
                Console.Write("Sorry. The number you entered does not exist in the array.");
                break;
            }
        }

            Console.ReadLine();
    }

    private static float readFloat(string question)
    {
        Console.Write(question);
        string ans = Console.ReadLine();
        float number = float.Parse(ans);
        return number;
    }

    private static int readNumber(string question)          
    {
        Console.Write(question);
        string ans = Console.ReadLine();
        int number = int.Parse(ans);
        return number;
    }
}

3 个答案:

答案 0 :(得分:3)

  

我遇到的问题是它不接受浮点数(仅限于   到目前为止整数工作),它只会找到第一个数字   输入

不接受浮点数并不清楚你的意思。如果您在尝试阅读解析浮动值时遇到任何异常,则必须告诉我们您的输入和CurrentCulture的示例。除此之外,我们无法帮助你解决这个问题。

你说;

  

“对于浮动问题,您是否尝试输入2.5或2,5取决于   在你的文化环境中,错误的将导致25“.2,5工作   (显示2,5)但2.5会导致未处理的异常。

太正常了。由于float.Parse(string)默认使用您的CurrentCulture设置 ,看起来像CurrentCulture使用,作为NumberDecimalSeparator,这就是为什么您成功将2,5解析为float,但2.5获得例外。

由于您对breakif部分使用else,因此在第一次迭代后它会在for循环之外消失。

来自$ 8.9.1 break声明seciton;

  

break语句退出封闭switchwhiledo最近的,   forforeach声明。

由于您想阅读所有元素,因此需要删除这些break语句。

如果您使用Visual Studio,则会在检测到无法访问的代码时收到i++部分的警告。

enter image description here

你的for循环对我来说也没什么意义。您为阵列中的每个项打印"Congratulations..""Sorry.."个字符串。我想你想只显示一次这些字符串,你可以使用Contains method作为你的数组;

if(numbers.Contains(userInput))
{
   Console.Write("Congratulations! The number you entered exists in the array.");
}
else
{
   Console.Write("Sorry. The number you entered does not exist in the array.");
}

答案 1 :(得分:0)

您可以使用

float.Parse(ans, CultureInfo.InvariantCulture.NumberFormat);

祝你好运

答案 2 :(得分:0)

除非您想要找到匹配的浮点数以外的其他操作,否则您不需要 mContentResolver.update(ChatProvider.CONTENT_URI, values, ChatProvider.ChatConstants.JID +"= '"+JID+"' and "+ChatProvider.ChatConstants.GROUP_CHAT_SENDER_NAME+"= '"+group_chat_sender_ph_no+"' and "+ChatProvider.ChatConstants.DATE+"= '"+ts+"'", new String[]{/*add selection args*/}); 语句。

在你的else语句中,else实际上正在完成它的工作并打破语句并退出范围。

break

然后它应该工作正常!

除了逻辑错误之外,还有评论中提到的@AntiHeadshot:

  

输入2.5或2,5,取决于您的文化设置错误的一个   将导致25