【问题标题】:Segmentation Fault when using command-line arguments使用命令行参数时出现分段错误
【发布时间】:2020-09-03 03:23:42
【问题描述】:

我是编程新手。以下是我编写的用于计算随机 6 面掷骰子的概率分布的程序。它工作得很好,但是如果我使用命令行参数作为抛出次数,它会开始抛出分段错误错误。有人可以帮我理解我做错了什么吗?

// distribution of rand numbers

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

const unsigned short NUM_FACES = 6;

int main(int argc, char * argv[])
{
    if(argc != 2 || isdigit(argv[1]))
    {
        printf("Invalid arguments!!\n");
        printf("Usage: %s numThrows\n", argv[0]);                      //correct usage of arguments
        exit(EXIT_FAILURE);
    }

    system("clear");

    srand(time(0));                                                    //updating seed
    long upperLim = atol(argv[1]);
    long dist[7] = {0};
    double probab = 0.0;
    unsigned int i;
    for(i = 0; i < upperLim; i++)
        ++dist[rand()%6 + 1];                                         //generating random numbers (1-6)

    for(i = 0; i < NUM_FACES; i++)
    {
        probab = 100.0*dist[i]/upperLim;                              //calculating probability of each throws
        printf("DICE THROW %d ->     Number of throws: %ld     Distribution: %.2lf%c\n", i+1, dist[i], probab, '%');
    }

    getchar();
    return 0;
}

【问题讨论】:

    标签: c command-line-arguments random-seed


    【解决方案1】:
    isdigit(argv[1])
    

    isdigit希望int,不是char *

    如果您想要CKEEK,如果所有字符是数字,则可以使用类似的东西:
    bool strIsDigit(const char *str)
    {
        while (*str)
        {
            if (!isdigit((unsigned char)*str++))
            {
                 return false;
            }
        }
        return true;
    }
    

    【讨论】:

    • 欢迎您;),您应该始终在 span>上编译警告
    猜你喜欢
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2020-11-19
    • 2014-03-22
    相关资源
    最近更新 更多