[英]Segmentation Fault when using command-line arguments
我是編程新手。 以下是我編寫的一個程序,用於計算隨機 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;
}
isdigit(argv[1])
isdigit
想要一個int
,而不是一個char *
如果你想檢查所有字符是否都是數字,你可以使用類似的東西:
bool strIsDigit(const char *str)
{
while (*str)
{
if (!isdigit((unsigned char)*str++))
{
return false;
}
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.