2012-07-15 79 views
0

有人可以請看看這段代碼,並幫助我確定爲什麼我沒有輸出總和for循環退出時?沒有輸出總和在c#程序

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(); 
     } 
    } 
} 
+1

'class RandomNumbers {'缺少的開始大括號。 – 2012-07-15 21:11:48

+1

你初始化'i'兩次。相反,你應該在for循環中聲明自己(而不是之前):'for(int i = 1; i <100; i ++){...}' – 2012-07-15 21:14:01

+0

感謝Tim ~~'class RandomNumbers '是在自己的路線上。我會記住索引變量的正確初始化(在for循環中,而不是在之前)。 -m – user1527399 2012-07-15 21:34:32

回答

8

你正在做

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

而是使用{n},其中n是格式字符串之後的第n個參數Console.WriteLine,即

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

here有關格式字符串的詳細信息。

+0

完全解決了它!我是一個「小白菜」:P!謝謝。一直盯着它... – user1527399 2012-07-15 21:27:23

+0

沒問題!很高興答案幫助。 – Bort 2012-07-15 21:29:08

+0

@ user1527399:然後你應該[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – 2012-07-15 21:48:57