Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#变量int采用不同的值_C#_Variables_Input - Fatal编程技术网

C#变量int采用不同的值

C#变量int采用不同的值,c#,variables,input,C#,Variables,Input,我正在尝试创建一个简单的程序来计算平均值。用户应该输入一个正数,然后我创建一个循环,从0到输入的数字求和。然后,平均值是总数除以输入的数字 问题:当我输入一个数字时,例如10,变量变为58。对于我输入的任何值,它总是加48。有人知道这个问题吗 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; names

我正在尝试创建一个简单的程序来计算平均值。用户应该输入一个正数,然后我创建一个循环,从0到输入的数字求和。然后,平均值是总数除以输入的数字

问题:当我输入一个数字时,例如10,变量变为58。对于我输入的任何值,它总是加48。有人知道这个问题吗

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace inClass1
{
    class Loops
    {
        static void Main(string[] args)
        {
            int total = 0;
            int num;
            Console.Write("Enter a positive number: ");

            num = Convert.ToInt32(Console.Read());

            for (int i = 0; i <= num; i++)
            {
                total = total + i;
            }

            double average = total / (double)num;
            Console.WriteLine("The average is = " + average);
            Console.ReadLine();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间inClass1
{
类循环
{
静态void Main(字符串[]参数)
{
int-total=0;
int-num;
Console.Write(“输入正数:”);
num=Convert.ToInt32(Console.Read());

对于(int i=0;i这是因为
Console.Read
方法读取第一个
char
并返回其
ASCII
值。并且它只读取一个char,因此您不能同时读取多个数字。要解决此问题,只需使用
Console.ReadLine
字符串作为输入:

 um = Convert.ToInt32(Console.ReadLine());

如果用户输入了无效的数字,则此操作将失败。为了防止出现这种情况,您可以查看方法。

问题在于您使用的是
控制台。请阅读

该方法返回一个
int
,而不是
字符串
。该int是读取字符的Unicode字符代码。获取int的
Convert.ToInt32
重载如下所示:

public static int ToInt32(int value) {
        return value;
    }

这意味着它只是返回传递的值(而不是解析)。Unicode“1”是数字49


相反,使用
Console.ReadLine
,它除了获取整个输入(而不仅仅是第一个字符)外,还将返回一个字符串,这样当您使用
Convert.ToInt32

@Selman22哇,这就是我不仔细阅读文档得到的结果。修复了。不是ASCII;Unicode(根据Console.InputEncoding进行翻译后)“@TomBlodget有趣,在这种情况下它们是一样的。感谢您的澄清。这是一个很好的学习机会,每个程序员都应该知道。这将是一个很好的面试问题…@HansPassant我不同意。我认为很多程序员不需要知道ASCII。但几乎所有的程序员都需要知道。谢谢@Se。”lman22,成功了!我来看看int.Parse方法!