I have a problem when use recursive method call.
I know the problem here setInfo(ref name, ref age, ref address, ref country);
, but I don’t know how to fix it.
class person{
private string name;
private short age;
private string address;
private string country;
public person(){
Console.Write("Hi i'm constructor nn");
}
public void setInfo(ref string name, ref short age, ref string address, ref string country){
if (name != "" || address != "" || country != "" || age != 0) {
this.name = name;
this.age = age;
this.address = address;
this.country = country;
} else {
setInfo(ref name, ref age, ref address, ref country); // Here is what I doubt.
}
}
public void getInfo(){
Console.Clear();
Console.WriteLine("---- The information ----nName: {0}nAge: {1}nAddress: {2}nCountry: {3}", this.name, this.age, this.address, this.country);
}
}
// When usage
static void Main(string[] args){
string name, address, country;
short age;
person one = new person();
Console.Write("Name: ");
name = Console.ReadLine();
Console.Write("Age: ");
Int16.TryParse(Console.ReadLine(), out age);
Console.Write("Address: ");
address = Console.ReadLine();
Console.Write("Country: ");
country = Console.ReadLine();
one.setInfo(ref name, ref age, ref address, ref country);
one.getInfo();
}
Загрузка…
здравствуйте.
Выходит ошибка «Ошибка времени выполнения: StackOverflowException: Программа завершена из-за переполнения программного стека». В чем ошибка, не пойму.
Вот задача
(Е. Джобс) Алгоритм вычисления функции F(n), где n – натуральное число, задан следующими соотношениями:
F(n) = n + 1 при n < 3,
F(n) = n + 2*F(n + 2), когда n ≥ 3 и четно,
F(n) = F(n – 2) + n – 2, когда n ≥ 3 и нечетно.
Сколько существует чисел n, для которых значение F(n) будет трехзначным.
Ответ известен : 22
Ниже мой проект программы:
//Функция F
function F(n: integer): integer;
begin
if n < 3 then
F := n + 1
else
if ((n mod 2) = 0) then
F := n + 2 * F(n + 2)
else
F := F(n — 2) + n — 2;
end;
var
cikl, kolvo: integer;
//Основная часть программы, где запускаем функцию.
begin
kolvo := 0;
for cikl := 1 to 100 do
begin
if (F(cikl) >= 100) and (F(cikl) <= 999) then
kolvo := kolvo + 1;
end;
WriteLn(cikl);
end.
This is difficult situation to explain. Have a service process that starts 2 threads, each thread loops forever but sleeps for 5 minutes each once the payload is finished.
Problem is that my second thread terminates well before the payload is even finished, for no apparent reason, and i also can’t catch the exception as it seems to be triggered from outside the delegate process?
Any suggestions on how to find the problem?
The code….
public void StartService()
{
ThreadStart stRecieve = new ThreadStart(DownloadNewMail);
ThreadStart stSend = new ThreadStart(SendNewMail);
senderThread = new Thread(stRecieve);
recieverThread = new Thread(stSend);
sendStarted = true;
recieveStarted = true;
senderThread.Start();
recieverThread.Start();
}
private void DownloadNewMail()
{
while(recieveStarted)
{
//Payload....
if (recieveStarted)
{
Thread.Sleep(new TimeSpan(0, confSettings.PollInterval, 0));
}
}
}
private void SendNewMail()
{
while(sendStarted)
{
//Payload....
if (sendStarted)
{
Thread.Sleep(new TimeSpan(0, confSettings.PollInterval, 0));
}
}
}
asked Dec 15, 2010 at 11:10
Jan de JagerJan de Jager
8702 gold badges13 silver badges35 bronze badges
6
Try to check callstack lenght in your code:
class Program
{
static void Main(string[] args)
{
try
{
Hop();
}
catch (Exception e)
{
Console.WriteLine("Exception - {0}", e);
}
}
static void Hop()
{
CheckStackTrace();
Hip();
}
static void Hip()
{
CheckStackTrace();
Hop();
}
static void CheckStackTrace()
{
StackTrace s = new StackTrace();
if (s.FrameCount > 50)
throw new Exception("Big stack!!!!");
}
}
answered Dec 15, 2010 at 12:09
acoolaumacoolaum
2,1122 gold badges15 silver badges24 bronze badges
If you are having trouble following the flow of your application’s code execution, try logging the entrance of methods with a timestamp and threadid.
Also, You can’t catch the exception because it is a StackOverflowException.
See msdn: «Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop. «
answered Dec 15, 2010 at 11:25
Eric DahlvangEric Dahlvang
8,2324 gold badges29 silver badges50 bronze badges
1
Do you utlize any heavy-weight library for tasks like DownloadNewMail and SendNewMail? For example I encountered StackOverflows when running large jobs using Microsoft.SqlServer.Dts.Runtime.Package. Try running the same workload sequentially inside a command-line application to see if the issue persists.
answered Dec 15, 2010 at 12:28
Oleg ZhylinOleg Zhylin
1,29012 silver badges18 bronze badges
1
Формулировка задачи:
Помогите пожалуйста исправить!!! Писал простенький тригонометрический калькулятор. Я так понимаю ошибка из-за рекурсии в модуле, но я не знаю как ее устранить.
Модуль:
Основная программа:
Код к задаче: «Ошибка времени выполнения: StackOverflowException: Программа завершена из-за переполнения программного стека»
textual
Function Sin(x:real) :real; begin writeln('Синус угла= ',PABCSystem.sin(x*pi/180):0:3); end;
Полезно ли:
7 голосов , оценка 4.714 из 5