您好,我的程序跳过for循环,我不知道为什么

时间:2018-03-11 17:08:43

标签: c#

using System;
using System.Collections.Generic;

namespace c3
{
    class Program
    {
        static int sumaTotala;
        static void Main(string[] args)
        {
            int teza;
            int numberOfNotes;
            Console.WriteLine("Numar de note: ");
            numberOfNotes = Convert.ToInt32(Console.ReadLine());
            List<int> numarDeNote = new List<int>(numberOfNotes);
            for (int i = 1; i < numarDeNote.Count + 1; i++)
            {
                Console.WriteLine("Introdu " + i + " nota: ");
                int x = Convert.ToInt32(Console.ReadLine());
                numarDeNote.Add(x);
                sumaTotala += x;
            }
            Console.WriteLine("Teza : ");
            teza = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Media a rezultat " + NumberInput(numarDeNote, teza, numberOfNotes));
            Console.ReadKey();
        }
        static float NumberInput(List<int> numarNote, int notaTeza, int numarxd)
        {
            float part1 = sumaTotala / numarxd;
            float part2 = part1 * 3;
            float part3 = part2 + notaTeza;
            float part4 = part3 / 4;
            return part4;
        }
    }
}

3 个答案:

答案 0 :(得分:2)

numarDeNote.Count的值从0开始,i从1开始,因此for循环中的条件i < numarDeNote.Count + 1永远不会成立。所以循环体永远不会被执行。

创建列表时指定一个值意味着初始列表对于那么多条目有增长空间,但最初仍然没有条目。

答案 1 :(得分:1)

List的构造函数只设置容量
在您添加项目

之前,它的计数仍为零

List Constructor (Int32)

使用

for (int i = 1; i < numberOfNotes + 1; i++)
{

答案 2 :(得分:-2)

中的构造函数参数
List<int> numarDeNote = new List<int>(numberOfNotes);

Capacity,而不是已创建列表的Count

for (int i = 1; i < numberOfNotes + 1; i++)
{
  ...
相关问题