我主要是一名电子硬件人员,但我从 friend 那里学到了 D 的基础知识,所以我决定选择一种更标准的语言,比如 C。所以,任何建议都会很好。 基本上,我使用整数“phew”作为计数器,来反转所有数字。 super 基本,但我很难找到在 C 中执行此操作的方法。我的代码:
#include <stdio.h>
int main()
{
int input;
int phew;
printf("Binary Number: ");
scanf("%d", &input);
while(phew < sizeof(input))
{
if(input[phew] == 0)
printf("1");
else
printf("0");
phew++;
}
return 0;
}
编译器错误是:
helloworld.c: In function ‘main’:
helloworld.c:11:11: error: subscripted value is neither array nor pointer nor vector
if(input[phew] == 0)
^
最佳答案
首先,在下面的声明中,
while(phew < sizeof(input))
调用undefined behavior如
phew
是一个自动局部变量且未初始化。您需要初始化phew
喜欢int phew = 0;
在这种情况下,
sizeof(input)
有效,但没有任何意义。
也就是说,您只能使用 []
数组类型上的运算符。在你的情况下,input
是 int
,所以你不能写 input[n]
.
详细说明,引用 C11
标准,第 §6.5.2.1 章
Syntax
postfix-expression
[
expression]
和描述
One of the expressions shall have type pointer to complete object type, the other expression shall have integer type, and the result has type type.
所以,很明显,在你的情况下input
不是“类型指针”,因此会出现错误。
解决问题,
您可以更改
input
的类型如char input[32] = {0};
将扫描语句更改为 `scanf("%29s", input);
添加
while(phew < strlen(input))
有道理。您将需要string.h
头文件。查看 strlen()
here的详细信息.
你必须像这样改变它
while(phew < strlen(input) )
{
if(input[phew] == '0') //ASCII 48, decimal
printf("1");
else
printf("0");
phew++;
}
关于C语言计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34877834/