यह प्रश्न थोड़ा पुराना प्रतीत होता है, लेकिन चूंकि मैंने एक ही समस्या के बारे में ठोकर खाई: अलेक्जेंडर टोरस्टलिंग का उत्तर और नीचे दी गई टिप्पणियां वास्तव में मेरे लिए अच्छी तरह से काम करती हैं।
क्या अच्छा है कि सी # फ्लोटिंग पॉइंट अपवादों को सक्षम करने के लिए अपना स्वयं का तरीका प्रदान नहीं करता है, फिर भी यह उन्हें पकड़ सकता है (सी ++ के लिए आपको पहले रूपांतरण की आवश्यकता है)।
सी # -code यहाँ है:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
class Program
{
[System.Runtime.InteropServices.DllImport("msvcrt.dll")]
public static extern uint _control87(uint a, uint b);
[System.Runtime.InteropServices.DllImport("msvcrt.dll")]
public static extern uint _clearfp();
static void Main(string[] args)
{
float zero = 0.0f - args.Length; // Want 0.0f. Fool compiler...
System.Console.WriteLine("zero = " + zero.ToString());
// A NaN which does not throw exception
float firstNaN = zero/0.0f;
System.Console.WriteLine("firstNaN= " + firstNaN.ToString());
// Now turn on floating-point exceptions
uint empty = 0;
uint cw = _control87(empty, empty); // Debugger halts on this one and complains about false signature, but continue works.
System.Console.WriteLine(cw.ToString());
uint MCW_EM = 0x0008001f; // From float.h
uint _EM_INVALID = 0x00000010; // From float.h (invalid corresponds to NaN
// See http://www.fortran-2000.com/ArnaudRecipes/CompilerTricks.html#x86_FP
cw &= ~(_EM_INVALID);
_clearfp(); // Clear floating point error word.
_control87(cw, MCW_EM); // Debugger halts on this one and complains about false signature, but continue works.
System.Console.WriteLine(cw.ToString());
// A NaN which does throw exception
float secondNaN = 0;
try
{
// Put as much code here as you like.
// Enable "break when an exception is thrown" in the debugger
// for system exceptions to get to the line where it is thrown
// before catching it below.
secondNaN = zero/0.0f;
}
catch (System.Exception ex)
{
_clearfp(); // Clear floating point error word.
}
System.Console.WriteLine("secondNaN= " + secondNaN.ToString());
}
}
}
अपवाद मैं मिलता है { "ओवरफ्लो या अंकगणितीय संचालन में अधःप्रवाह।"} {System.Exception System.ArithmeticException}
सुनिश्चित नहीं हैं कि क्यों डीबगर _control87 के हस्ताक्षर के बारे में शिकायत करता है; कोई भी जो उस पर सुधार कर सकता है? "जारी रखें" मेरे लिए ठीक काम करता है, हालांकि।
स्रोत
2013-07-25 13:38:07
दुर्घटना का कारण क्या है? –
ऐसा लगता है कि यह एक ऐसा मामला है जहां विकास में परीक्षण शामिल करना चाहिए। यदि आपके गणित कार्य बहुत अधिक नहीं हैं तो आप पहले से ही पूर्व में वापस लौटने से बचने के लिए पूर्व-और पोस्टकंडिशन को सही तरीके से परिभाषित करना और उनके लिए परीक्षण लिखना चाहते हैं। – Frank
इस मामले में एक सरणी का उपयोग जहां सूचकांक = (लंबा) NaNvalue, लेकिन यह कुछ और हो सकता था। – Trap