2015-11-07 152 views
-4

我嘗試編譯這個小小的簡單程序,但我得到「調試斷言失敗」,有人可以解釋爲什麼嗎?調試斷言失敗 - argc和argv

#include <stdio.h> 
#include <stdlib.h> 

#define answer 3.14 

void main(int argc, char **argv) 
{ 
    float a = strtod(argv[1], 0); 

    printf("You provided the number %f which is ", a); 


    if(a < answer) 
      puts("too low"); 
    else if(a > answer) 
      puts("too high"); 
    else if (a == answer) 
      puts("correct"); 
} 

使用方法:

打開CMD,該.exe文件拖放到它,然後寫一個空格,然後通過一個號碼,按下回車鍵。例如。 C:\test.exe 240

+0

輕微:我想知道你爲什麼要用'double'混合'float'。值「3.14」與'strtod'的返回值一樣是'double'。最後,由於前面的測試沒有得到滿足,所以你最後一個'else if(a == answer)'是不必要的,無論如何,比較一個實際的等號並不好,尤其是比較'float'和'double'值。 –

+0

我知道我用double來混合浮動,但它起作用。是的,最後一次檢查不起作用,但這是另一個問題。 – Black

+1

'if(argc> 1)a = strtod(argv [1],0);' –

回答

0

我找到了一個可能的解決方案,但我不明白它爲什麼起作用。也許有人可以解釋爲什麼argc - 2

float a = (argc -2)? 0 : strtod(argv[1], 0); 
+1

它是驗證用戶輸入正確的命令:'test.exe someNumber'。也就是說,兩個參數('argc = 2')如果不是,你只要考慮輸入的數字是0。 –

1

外觀與評論這個重寫代碼(不是我編的話):

#include <cstdio> // Include stdio.h for C++ - see https://msdn.microsoft.com/en-us/library/58dt9f24.aspx 
#include <cstdlib> // Include stdlib.h for C++ - see https://msdn.microsoft.com/en-us/library/cw48dtx0.aspx 

#define answer 3.14 // Define value of PI as double value. 
        // With f or F appended, it would be defined as float value. 

int main(int argc, char **argv) 
{ 
    if(argc < 2) // Was the application called without any parameter? 
    { 
      printf("Please run %s with a floating point number as parameter.\n", argv[0]); 
      return 1; 
    } 

    // Use always double and never float for x86 and x64 processors 
    // except you have a really important reason not doing that. 
    // See https://msdn.microsoft.com/en-us/library/aa289157.aspx 
    // and https://msdn.microsoft.com/en-us/library/aa691146.aspx 

    // NULL or nullptr should be used for a null pointer and not 0. 
    // See https://msdn.microsoft.com/en-us/library/4ex65770.aspx 

    double a = strtod(argv[1], nullptr); 

    // %f expects a double! 
    printf("You provided the number %f which is ", a); 

    // See https://msdn.microsoft.com/en-us/library/c151dt3s.aspx 
    if(a < answer) 
      puts("too low.\n"); 
    else if(a > answer) 
      puts("too high.\n"); 
    else 
      puts("correct.\n"); 

    return 0; 
} 
0

此代碼工作完全在我的設置,如果我至少提供一個命令行參數。沒有任何爭論,它像預期的那樣崩潰。