0

我在使用 atoi(s) 函数时遇到了一些问题。我正在尝试将命令行参数转换为整数,但是我从 atoi 函数接收到的整数表现得很奇怪。我检查了持有转换的变量,它们持有正确的整数,但是当它们通过我的程序运行时,它们不能正常工作。该程序接受三个参数;程序本身、函数编号 (1-3) 和任意整数。例如,命令行指令看起来像 lab4p2 3 10。

职能:

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


//---------------------------------------------------------------------------
// Functions

// Sumation function adds all integers from 1 to the value.
int sumation(int x)
{
  int counter = 1;
  int value;
  while (counter < (x+1))
    {
      value += counter;
      counter++;
    }
  return value;
}

// Negation function returns the negation of the given value.
int negation(int x)
{
  int negator, value;

  negator = (x*2);
  value = (x - negator);
  return value;
}

// Square function returns the square of the input value.
int square(int x)
{
  int value;
  value = (x*x);
  return value;
}

//---------------------------------------------------------------------------

主要的:

main(int argc, char *argv[])
{

  int inputval, functionval, value;
  double doubleval;

  functionval = atoi(argv[1]);

  inputval = atoi(argv[2]);
  doubleval = atof(argv[2]);

  printf("%i", functionval);
  printf("%i", inputval);

  if(argc != 3)
    {
      printf("%s", "Invalid amount of arguments! 3 expected. \n");
    }
  else if ((functionval < 1)||(functionval > 3))
    {
      printf("%s", "Invalid function value. Expected values: 1-3 \n");
    }
  else if (inputval != doubleval)
    {
      printf("%s", "Invalid value! Integer expected. \n");
    }
  else if (functionval = 1)
    {
      value = sumation(inputval);

      printf("%s", "The sum from 1 to the input value = ");
      printf("%d", value);
    }
  else if (functionval = 2)
    {
      value = negation(inputval);

      printf("%s", "%d", "The negation of the input value = ", value);
    }
  else if (functionval = 3)
    {
      value = square(inputval);

      printf("%s", "%d", "The square of the input value = ", value);
    }
  else
    {
      printf("%s", "Something is wrong!");
    }

}

所有的错误检查都正常工作,但函数 2 和 3 永远不会被访问(尽管输入)并且函数 1 显示不正确的答案。有谁知道问题可能是什么?

谢谢,马特

4

2 回答 2

4
functionval = 1    assignment

functionval == 1   comparison

顺便说一句,当你得到 doubleval 时也有一个错字 现在我看到再次使用 argv[2] 和不同的转换函数是故意的,而不是 argv[3] 的错字,我建议如果你关心转换错误,你使用类似的东西:

errno = 0;
char* endptr;
long value = strtol(argv[2], &endptr, 10);
if (errno == ERANGE) {
  // Value was too big or too negative
} else if (endptr == argv[2] || errno == EINVAL) {
  // Not a number
} else if (endptr[0] != '\0') {
  // trailing characters.
}
// Value is OK.

如果你经常使用它,它值得包装成更容易调用的东西。

于 2012-10-08T01:01:40.333 回答
2
else if (functionval = 1)
else if (functionval = 2)
else if (functionval = 3)

应该

else if (functionval == 1)
else if (functionval == 2)
else if (functionval == 3)

否则,您将执行分配而不是比较。

于 2012-10-08T01:03:27.477 回答