我正在编写一个程序,它接收一个数字并给出除数的数量。 例如 在命令中:
practica -n 30
预期输出:
1,2,3,5,6,10,15,30
我有这个代码:
void divisor(char *temp1);
int main(int argc,char **argv){
int option;
char *n;
while((option =getopt(argc,argv,"n")) !=-1){
switch(option){
case 'n':
n=optarg;
break;
}
}
divisor(n);
}
void divisor(char *temp1){
char f=*temp1;
int n=f-'0';
int a;
a=1;
while (a<n)
{
if(n%a==0)
printf("%d,",a);
a++;
}
a=n;
if(n%a==0)
printf("%d",a);
printf("\b ");
}
我正在使用命令行,程序关闭。
最佳答案
我认为,您的 getopt()
调用应该类似于
while((option =getopt(argc,argv,"n:")) !=-1){ //notice the :
因为您将为该选项提供一个参数(值)。
也就是说,在您的代码中,在 divisor()
函数内,
char f=*temp1;
int n=f-'0';
看起来不对。 temp
是一个 char
指针,取消引用该指针只会给出存储的第一个 char
的值,以及预期值,30
不存储为单个 char
,而是存储为字典格式。
我想,你可以使用strtol()
将字典表示形式转换为 int
值,例如
int x = strtol(temp, NULL, 0);
关于c - 使用函数 getopt 得到除数的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31154441/