【问题标题】:Number of divisors with the function getopt具有函数 getopt 的除数数
【发布时间】:2015-09-18 04:54:17
【问题描述】:

我正在做一个程序,它接收一个数字并给你除数的数量。 例如 在 cmd 中:

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 ");
}

我正在使用命令行,程序关闭。

【问题讨论】:

  • 您是否尝试过调试您的应用程序以查看它实际出错的地方?

标签: c string command-line-arguments getopt


【解决方案1】:

我认为,您的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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多