这里是编程新手。我有一项作业,必须使用 getchar()
读取数字。并对其进行一些操作。该数字可以是正数或负数。这是我的代码中接受输入的部分。我找不到问题,但它返回了其他内容。
我使用将字符转换为整数的一般方法,首先将累加器乘以 10
,然后使用 (ch -'0')
将字符转换为其等效数字并将其添加到累加器中,
我已尝试删除对负数的验证,但仍然没有什么区别。
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
int main() {
int accumulator = 0;
char ch;
int negative = 0;
ch = getchar();
if (ch == '-') {
negative = -1;
ch = getchar();
}
if (isdigit(ch) == 0) {
puts("\nError: Not valid number.\nPlease try again");
EXIT_FAILURE;
}
while ((ch = getchar()) != '\n') {
ch = getchar();
if ((ch = getchar()) == EOF) {
break;
}
if (!isdigit(ch)) {
puts("\nError: Not valid number.\nPlease try again");
break;
EXIT_FAILURE;
}
accumulator = accumulator * 10;
accumulator = (ch = '0') + accumulator;
}
if (negative == -1)
accumulator = accumulator * negative;
printf("%d", accumulator);
}
示例
输入:2351
输出:2351
(使用getchar
)
输入:-5689
输出:-5689
(使用getchar
)
最佳答案
您在 while
循环中调用 getchar()
次数过多。他们每个人都丢弃前一个调用的结果。您应该只在 while()
条件中使用 getchar()
调用的结果,而不是再次调用它。
您也没有将循环之前读取的字符保存到累加器中。
ch = '0'
中有一个拼写错误,应该是 ch - '0'
。
您需要将 ch
声明为 int
,而不是 char
,因为 EOF
不是字符。
EXIT_FAILURE
应为exit(EXIT_FAILURE)
。并且您不应该在其前面放置 break;
,因为这将终止循环,跳过 exit()
调用。
您可以将负数
初始化为1
,因此最后您只需乘以它即可,而无需先测试该值。在这种情况下,更好的变量名称是 sign
。
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
int main() {
int accumulator = 0;
int ch;
int sign = 1;
ch = getchar();
if (ch == '-') {
sign = -1;
ch = getchar();
}
if (!isdigit(ch)) {
puts("\nError: Not valid number.\nPlease try again");
exit(EXIT_FAILURE);
}
accumulator = ch - '0';
while ((ch = getchar()) != '\n' && ch != EOF) {
if (!isdigit(ch)) {
puts("\nError: Not valid number.\nPlease try again");
exit(EXIT_FAILURE);
}
accumulator *= 10;
accumulator += (ch - '0');
}
accumulator *= sign;
printf("%d", accumulator);
}
关于c - 我无法使用 getchar() 读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978686/