gpt4 book ai didi

c# - 避免时钟程序中的溢出错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:47 25 4
gpt4 key购买 nike

嘿,我是一名初级编码员,我正在尝试在 Visual Studio 中制作一个控制台时钟程序。它可以工作,但大约 2 小时后,由于时钟在无限循环中运行,它会抛出堆栈溢出错误。这是我的代码-

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

namespace ConsoleApplication1
{
class Program
{
static string hourInput;
static string minuteInput;
static string yearInput;
static string dayInput;
static string monthInput;

static int saveMonth;
static int saveYear;
static int saveDay;
static int saveSeconds;
static int saveMinutes;
static int saveHours;


static void Main(string[] args)
{
Console.WriteLine("Enter the current hour");
hourInput = (Console.ReadLine());
saveHours = Int32.Parse(hourInput);

Console.WriteLine("Enter the current minute");
minuteInput = (Console.ReadLine());
saveMinutes = Int32.Parse(minuteInput);

Console.WriteLine("Enter the current day");
dayInput = (Console.ReadLine());
saveDay = Int32.Parse(dayInput);

Console.WriteLine("Enter the current month in numerical form");
monthInput = (Console.ReadLine());
saveMonth = Int32.Parse(minuteInput);

Console.WriteLine("Enter the current year");
yearInput = (Console.ReadLine());
saveYear = Int32.Parse(yearInput);


Update();
}

static void Update()
{
Counter();
}

static void Counter()
{
int days = 1;
int minutes = 0;
int hours = 1;
int Seconds = 0;
int months = 1;
int years = 2015;
bool dayOver = false;

Seconds = saveSeconds;
minutes = saveMinutes;

if (saveHours > hours)
{
hours = saveHours;
}

if (saveYear > years)
{
years = saveYear;
}

if (saveMonth > months)
{
months = saveMonth;
}

if (saveDay > days)
{
days = saveDay;
}

Seconds++;

if (Seconds == 60)
{
minutes++;
Seconds = 0;
}

if (minutes == 60)
{
hours++;
minutes = 0;
}

if (hours > 12)
{
if (dayOver == true)
{
days++;
dayOver = false;
}
else
{
dayOver = true;
}
hours = 1;
}

Console.Clear();

Console.WriteLine(days + ":" + hours + ":" + minutes + ":" + Seconds);

saveSeconds = Seconds;
saveMinutes = minutes;
saveHours = hours;

System.Threading.Thread.Sleep(1000);

Update();
}
}
}

那么有什么方法可以在不引发堆栈溢出的情况下运行无限循环?请记住,我是一名初级编码员,所以它不能太复杂。我知道还有其他方法可以执行时钟程序,但这是我想要的方法。

最佳答案

你得到一个 StackOverflow 是因为你递归地调用你的方法。

每次调用方法时,它都会被推送到调用堆栈。

如果您改为使用 while 循环,调用堆栈中唯一存在的方法(我们关心的)将是包含 while 循环的方法,因此不会出现堆栈溢出。

关于c# - 避免时钟程序中的溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34214181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com