我对 C 编程非常陌生,正在学习 K&R C 编程语言书籍。我正在尝试编写一个程序,将十六进制数重复转换为十进制数,并希望在我的代码中使用一个函数。有一些问题阻碍我理解 C。我读过它们,但还不清楚。
我想读取长度最大为4的输入,但据我了解,尽管char数组的长度是4,但scanf()并不限制长度。所以我尝试用for循环消除非整数字符。这个可以吗?获取用户输入的正确方法是什么?我不想使用 while((cr=getchar())!=EOF)
。
当我运行程序时,我收到一条错误消息:“未定义对‘转换’的引用”。我应该如何定义函数?
我使用 Code::Blocks 16.01 和 MinGW。
这是我的尝试:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#define LENGTH 4
int convert (char hex[]);
int result,validLength,j;
char input[LENGTH];
int main(){
while(1){
printf("Please enter valid hexadecimal number %d length:",LENGTH);
scanf("%c", input); //reading to char array
for(j=0;j<LENGTH;j++) // buffer
if(input[j] > 48 && input[j] < 58)
validLength++;
printf("Here is the decimal result: %d", convert(input[validLength]));
validLength=0;
}
int convert(char hex[]){
int t;
for(t=0; t < validLength; t++)
result= result+ hex[t]*(pow(16,(validLength-t)));
return result;
}
return 0;
}
最佳答案
1] 你不能有嵌套函数。将其移出体外。
2]这里
printf("Here is the decimal result: %d", convert(input[validLength]));
您传递的是 char
,但 convert
函数期望的是 char*
。正确:
printf("Here is the decimal result: %d", convert(input));
3] %c
说明符用于字符,使用 %s
以及读取多少个字符 %4s
更好。不要忘记检查返回值,例如
if(scanf("%4s", input) != 1)
{
// Fail
}
关于c - 如何解决C中的 undefined reference 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45597246/