-1

有人可以看看这段代码并帮助我确定为什么在退出 for 循环时我没有得到 sum 的输出吗?

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

/*This program finds 100 3 digit numbers between 100 and 1000, prints the message: "Cha, Cha, Cha!" after every 10th number, and outputs the sum of the numbers */

namespace MikeVertreeseRandom
{
    class RandomNumbers    //using the random class for number generation 
    {
        static void Main(string[] args)
        {
            Random r = new Random();

            int number = 0; //r.Next() finds the next random # bet 100 and 1000

            int sum = 0;  //declaring the variable "numberTotal" for the sum 

            int i = 1;            //i is the index counter

            for (i = 1; i < 100; i++)  //the program will run through 100 iterations
            {
                number = r.Next(100, 1000);

                Console.WriteLine(number); //program prints the next random #

                sum += number; //need to keep a running sum of the numbers found

                if ((i % 10) == 0)    //every 10th iteration, do something
                {

                    Console.WriteLine("Cha, Cha, Cha!"); //prints this message every 10th number
               }
           }

           Console.WriteLine("The sum is: []", sum);
           Console.ReadLine();
       }
   }
}
4

2 回答 2

7

你在做

Console.WriteLine("The sum is: []", sum);

而是使用{n},其中 n 是Console.WriteLine格式字符串之后的第 n 个参数,即

Console.WriteLine("The sum is: {0}", sum);

有关格式字符串的更多信息,请参见此处

于 2012-07-15T21:08:52.927 回答
0

复合格式中,需要匹配的大括号(“{”和“}”)。

于 2012-07-15T21:12:58.810 回答