2015-11-07 150 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

此代码工作完全在我的设置,如果我至少提供一个命令行参数。没有任何争论,它像预期的那样崩溃。