【发布时间】:2013-09-30 08:09:08
【问题描述】:
我正在上课,我们的作业是以下问题。我不确定我是否对这个问题读得太多了,或者根本不理解它。我知道如何设置随机数,但我一直坚持如何允许用户指定将多少个数字保存到文件中。任何帮助都会很棒。
问题: 编写一个程序,将一系列随机数写入文件。 每个随机数应在 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();
}
}
}'
【问题讨论】:
-
我只是想弄清楚如果用户输入他们想要 10 个随机数或 5 个随机数的去向。
-
你在写什么类型的程序?根据我们谈论的是控制台应用程序、表单应用程序还是网站,用户输入的方法会有很大差异。
-
对不起,这是一个表单应用程序。
-
好的,这就是我目前所拥有的。它在大多数情况下都有效,但是当用户保存文本文件时,它只保存最后生成的随机数,而不是生成的所有数字。
-
单步执行代码,您将看到为什么只保存最后一个数字。提示:“创建随机数列表”的注释与代码实际所做的不匹配。
标签: visual-studio random