我在使用 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 显示不正确的答案。有谁知道问题可能是什么?
谢谢,马特