所以我写了一个简单的程序,把一个十进制转换成二进制,它只接受正整数。因此,像-2和1.1这样的数字会输出“对不起,这不是一个正整数。”它无限地要求用户输入一个数字,直到用户按下ctrl + D为止。然而,当我测试它时,它打印出了“对不起.”语句,然后再结束程序。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
void DecToBin(int userInput){
int binary[32];
int i = 0;
while (userInput > 0) {
binary[i] = userInput % 2;
userInput /= 2;
i++;
}
for (int j = i - 1; j >= 0; --j) {
printf("%d", binary[j]);
}
}
int main(void) {
double userDec;
int temp;
printf("Starting the Decimal to Binary Converter!\n\n");
while(!feof(stdin)) {
printf("Please enter a positive whole number (or EOF to quit): ");
scanf("%lf", &userDec);
temp = (int)(userDec);
if ((userDec > 0) && (temp / userDec == 1)) {
printf("\n\t%.0lf (base-10) is equivalent to ", userDec);
DecToBin(userDec);
printf(" (base-2)!\n\n");
}
else {
printf("\tSorry, that was not a positive whole number.\n");
}
}
printf("\n\tThank you for using the Decimal to Binary Generator.\n");
printf("Goodbye!\n\n");
return 0;
}(所有的制表符和换行符都是它应该如何格式化的,所以不要注意这一点)因此,据我所理解,我的程序将ctrl + D作为我的while循环中的其他部分。知道为什么吗?
发布于 2021-03-13 21:17:04
似乎你认为code会在代码中触发某种破坏。比如关键字break。这不是真的。
阅读这篇文章,看看当您按C-d:https://stackoverflow.com/a/21365313/6699433时发生了什么
这并不会导致在C代码中发生任何特殊的事情。scanf根本不会读任何东西。在scanf语句之后,代码将一如既往地继续,因此代码将无条件地输入if语句。
这也是一件非常严重的事情,因为您将使用未初始化的userDec。scanf返回成功分配的数量,您应该始终检查返回值。所以在你的情况下你想要这个:
if(scanf("%lf", &userDec) != 1) { /* Handle error */ }因为如果scanf不返回1,则userDec未分配。
要实现你想要的,只需这样做:
if(scanf("%lf", &userDec) != 1)
break;https://stackoverflow.com/questions/66618458
复制相似问题