【发布时间】:2019-05-14 04:48:16
【问题描述】:
基本上,我正在尝试使用我对 C 的(基本)知识创建 d&d 骰子滚轮。在 for-loop 中,它应该循环输入并返回骰子中的边数,strlen()似乎返回两个单独的值:1.正确的值,2.一个非常大的数字。我不知道为什么它会返回第二个数字,这会弄乱for-loop。
我尝试将strlen() 分配给另一个名为length 的变量,并在我使用strlen() 的函数中调用它。每次我在输入dice_inp 存在的函数中打印strlen() 时,它都会打印正确的值,但是一旦我将它传递给sides(),它就会返回非常大的数字。
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <math.h>
int num();
int sides();
int main()
{
printf("This is a dice rolling simulator for D&D!\n");
int num_dice, num_sides;
num_dice = num();
num_sides = sides();
printf("num %d sides %d", num_dice, num_sides);
}
int num()
{
int i, keynum, dice_num = 0, length;
char dice_inp[20];
printf("Input the number of dice(n), then d,then the number of sides of each dice(s) so the input appears n the form 'nds'!\n");
scanf("%s", dice_inp);
length = abs(strlen(dice_inp));
keynum = strcspn(dice_inp, "d");
for (i = 0; i < keynum; i++)
{
char c = dice_inp[keynum - 1 - i];
c = c - '0';
c = round(c*pow(10, i));
dice_num += c;
}
if (dice_num == 1)
{
printf("There is %d dice being rolled.\n", dice_num);
Sleep(500);
}
else if (dice_num == 0)
{
printf("You cannot roll 0 dice.\n");
Sleep(500);
num();
}
else if (dice_num > 1)
{
printf("There are %d dice being rolled.\n", dice_num);
Sleep(500);
}
Sleep(500);
sides(length, dice_inp, keynum);
return dice_num;
}
int sides(int length, char dice_inp[], int keynum)
{
int i, dice_sides = 0;
for (i = 0; i < abs((length - keynum - 1)); i++)
{
char c = dice_inp[strlen(dice_inp) - 1 - i];
c = c - '0';
c = round(c*pow(10, i));
dice_sides += c;
printf("a");
}
if (dice_sides == 1)
{
printf("A dice cannot have one side. Please try again!\n");
Sleep(500);
num();
}
else if (dice_sides == 0)
{
printf("A dice cannot have 0 sides. Please try again.\n");
Sleep(500);
num();
}
else if (dice_sides > 1)
{
printf("The dice will have %d sides.\n", dice_sides);
Sleep(500);
}
printf("%d", dice_sides);
}
【问题讨论】:
-
为什么要在
abs(strlen(dice_inp));中使用abs? -
@Swordfish Dungeons and Dragons 使用不同面数的骰子,而不仅仅是传统的 6 面骰子。
-
你为什么不直接使用
scanf("%dd%d", &dice_num, &sides)? -
您确定您的问题源自函数
num中的sides(length, dice_inp, keynum)调用,而不是源自函数main中的num_sides = sides()调用吗? -
当您从
num()内部调用sides()时,您不会使用结果。然后在main()中调用它时不带参数,这会导致未定义的行为。