0

我正在上课,我们的作业是以下问题。我不确定我是否对这个问题读得太多了,或者根本不理解它。我知道如何设置随机数,但我一直坚持如何允许用户指定将多少个数字保存到文件中。任何帮助都会很棒。

问题:编写一个程序,将一系列随机数写入文件。每个随机数应该在 1 到 100 的范围内。应用程序应该让用户指定文件将保存多少个随机数。

这就是我到目前为止所拥有的。它的工作原理是文本文件只保存最后生成的随机数而不是所有随机数。

'using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Random_Number
{
    public partial class Form1 : Form
    {
        // Variable
        int result = 0;

        public Form1()
    {
        InitializeComponent();
    }

    private void generateButton_Click(object sender, EventArgs e)
    {
        try
        {
            // Get how many random numbers the user wants
            int myRandomNumbers = int.Parse(howManyTextBox.Text);

            // Create the random object
            Random rand = new Random();

            for (int i = 0; i < myRandomNumbers; i++)
            {
                // Create the list of random numbers
                result = rand.Next(1, 101);

                // Display the random numbers in the ListBox
                randomNumbersListBox.Items.Add(result);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void saveAs_Click(object sender, EventArgs e)
    {
         StreamWriter outputFile;

         if (saveFile.ShowDialog() == DialogResult.OK)
         {
                 // Create the selected file
                 outputFile = File.CreateText(saveFile.FileName);

                 // Write data to the file
                 outputFile.WriteLine(result);

                 // Close the file
                 outputFile.Close();
         }
         else
         {
             MessageBox.Show("Operation Cancelled");
         }
    }

    private void clearButton_Click(object sender, EventArgs e)
    {
        // Clear the ListBox and TextBox
        howManyTextBox.Text = "";
        randomNumbersListBox.Items.Clear();
    }

    private void exitButton_Click(object sender, EventArgs e)
    {
        // Close the program
        this.Close();
    }
}
}'
4

1 回答 1

1
class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter count: ");
        var count = int.Parse(Console.ReadLine());

        Console.Write("Writing numbers... ");
        WriteNumbers(count);
        Console.WriteLine("Done.");
    }

    static void WriteNumbers(int count)
    {
        var gen = new Random();

        var file = new StreamWriter("YourFile.txt", false);

        for (var i = 0; i < count; i++)
        {
            file.Write(gen.Next(1, 100) + " ");
        }

        file.Close();
    }
}
于 2013-09-30T08:23:46.020 回答