繁体   English   中英

在C#编程中的While循环

[英]While loops in programming C#

我正在尝试创建一个程序,该程序向用户询问整数并在while循环内将它们加起来,然后当输入负数时,循环结束,但是由于某种原因,我找不到添加方法用户添加到总数中的数字,它只显示小数(用户输入的金额)旁边最初是0的总数

int iNumber =0;
int iTotal = 0;
int iSubTotal = 0;

//Prompt user to enter two values
Console.WriteLine("Enter value you want to add to total value or a negative number to end the loop");

while (iNumber >= 0)
{
    iSubTotal = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("The Total is now " + iSubTotal + iTotal);

    if (iNumber < 0)
    {
        Console.WriteLine("You have not passed the loop");
        Console.WriteLine("The Total is now " + iTotal);
    }

    //Prevent program from closing
    Console.WriteLine("Press any key to close");
    Console.ReadKey();
}

您永远不会在代码中修改iSubTotaliTotal 因此,它们的价值永远不变。

您可能需要在循环中的某个位置修改值:

// ...
iSubTotal = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The Total is now " + iSubTotal + iTotal);
iTotal += iNumber;
// ...

编辑:根据您的以下评论,听起来您需要更稳健地处理输入。 如果字符串不可转换为整数,则Convert.ToInt32()将失败。 您可以使用以下方法使它更加健壮:

if (int.TryParse(Console.ReadLine(), out iSubTotal))
{
    // Parsing to an integer succeeded, iSubTotal now contains the new value
}
else
{
    // Parsing to an integer failed, respond to the user
}

您没有在此处为变量“ iSubTotal + iTotal”分配加法

iTotal += iSubTotal;
Console.WriteLine("The Total is now " + iTotal);

代替这两行

iSubTotal = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The Total is now " + iSubTotal + iTotal);

那是因为

 Console.WriteLine("The Total is now " + iSubTotal + iTotal);

是不正确的。 如果将两个数字加在一起,则需要将答案存储在某个位置,而不是在使用Console时存储。将+符号用于连接不加。

您永远不会更改iNumber或iTotal。 我认为这样的事情更是您最想要的。

while (iNumber >= 0)
    {
        iNumber = Convert.ToInt32(Console.ReadLine());
        iTotal += iNumber;
        Console.WriteLine("The Total is now " + iSubTotal + iTotal);
...

iSubTotal + iTotal

应该

(iSubTotal + iTotal)

否则,将其作为字符串读取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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