我有一个要求数字(int x)的程序。然后,用户应该向控制台输入x号码。并且控制台应该将所有数字加在一起并写出所有输入数字的结果。所以我做到了这一点:
Console.WriteLine("Enter an number: ");
int x = int.Parse(Console.ReadLine());
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ",i );
double numbers= double.Parse(Console.ReadLine());
}
Console.WriteLine("Sum of the entered numbers are: {0} ",x);
Console.ReadLine();
但结果只给了我最后输入的数字。我做错了什么?
答案 0 :(得分:3)
您需要创建一个变量,用于存储数字之和(sum
)。
然后,在您阅读下一个数字后,您应将其添加到您的总和中。
Console.WriteLine("Enter a number: ");
int x = int.Parse(Console.ReadLine());
double sum = 0;
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ", i);
double number = double.Parse(Console.ReadLine());
sum += number;
}
Console.WriteLine("Sum of the entered numbers is: {0}", sum);
Console.ReadLine();
答案 1 :(得分:1)
AGRN:exon.1 4.5714285 3.16742% (221 (# of lines in `6' / 7 #3 of lines `< 30`)
答案 2 :(得分:0)
这样就会显示输入数字的总和
Console.WriteLine("Enter an number: ");
int x = int.Parse(Console.ReadLine());
double sum = 0
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ",i );
sum = sum + double.Parse(Console.ReadLine());
}
Console.WriteLine("Sum of the entered numbers are: {0} ",sum);
Console.ReadLine();
答案 3 :(得分:0)
您实际上从未在代码中进行任何求和。
double sum = 0;
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ",i );
double numbers= double.Parse(Console.ReadLine());
sum += numbers;
}
Console.WriteLine("Sum of the entered numbers are: {0} ",sum);
答案 4 :(得分:0)
你可以这样做
Console.WriteLine("Enter an number: ");
int x = int.Parse(Console.ReadLine());
List<double> allNumbers = new List<double>();
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ",i );
double temp;
if(double.TryParse(Console.ReadLine(), out temp))
allNumbers.Add(temp);
else
Console.WriteLine("Enter a valid number");
}
Console.WriteLine("Sum of the entered numbers are: {0} ",allNumbers.Sum());
Console.ReadLine();
答案 5 :(得分:0)
这里有代码,Write
和WriteLine
格式正确。
Console.Write("Enter an number: ");
int x = int.Parse(Console.ReadLine());
double sum = 0;
for (int i = 0; i < x; i++)
{
Console.Write("Ange tal {0}: ", i);
double number = double.Parse(Console.ReadLine());
sum = sum + number;
}
Console.WriteLine("Sum of the entered numbers are: {0:R} ", sum);
Console.Write("Press a key to exit");
Console.ReadKey();
但现在我们想向前迈出一步:尝试插入:
2
0.1
0.2
(或0,1
和0,2
如果您使用,
作为小数点分隔符)
我一直认为OMG Ponies!!! (Aka Humanity: Epic Fail)是最好的阅读......
答案 6 :(得分:0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace add
{
class Program
{
static void Main(string[] args)
{
int a,b,c;
Console.WriteLine("Enter the first number");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second number");
b = Convert.ToInt32(Console.ReadLine());
c = a + b;
Console.WriteLine("The addition of two number is {0}", c);
Console.ReadLine();
}
}
}