This question already has an answer here:
Closed 4 years ago.
Why is C printing outputs late?
(1个答案)
我编写了以下代码(它是一个caclulator,获取3个运算符(+/-/$)和2个自然数(a,b)中的1个和计算数(a op b)(a$b被定义为a+(a+1)+…+(b-1)+b对于ab,它没有定义):
#include <stdio.h>
#include <stdlib.h>

int main() {

printf("Please choose an operation (+/-/$): ");
char op;
scanf("%c", &op);
while (op != '+' && op != '-' && op != '$') {
    printf("\nInvalid operation. Please choose again: ");
    scanf("%c", &op);
}
int a;
int b;
char term;
printf("\nPlease enter the first operand: ");
int scanCheck = scanf("%d%c", &a, &term);
while (scanCheck != 2 || term != '\n' || a < 0) {
    printf("\nInvalid number\n. Please enter the first operand: ");
    scanCheck = scanf("%d%c", &a, &term);
}
printf("\nPlease enter the second operand: ");
scanCheck = scanf("%d%c", &b, &term);
while (scanCheck != 2 || term != '\n' || b < 0) {
    printf("\nInvalid number\n. Please enter the first operand: ");
    scanCheck = scanf("%d%c", &b, &term);
}

if (op == '$' && a > b)
    printf("\nThe result is: Not Valid");

int result;
switch (op) {
case '+':
    result = a + b;
    break;
case '-':
    result = a - b;
    break;
case '$':
    result = 0;
    while (a <= b) {
        result += a;
        a++;
    }
    break;
}
printf("\nThe result is: %d", result);
return 0;
}

我的问题是,当我运行这个程序时,它什么也不打印。但是,在给程序一个输入(如+,3,4)之后,它会打印出它应该打印的行(有正确的结果)。为什么会这样?我该怎么解决?仅供参考,我使用eclipse Juno和minGW编译器。

最佳答案

您可能希望在print语句的末尾而不是开头添加“\n”:缓冲区可能不会刷新,因此会延迟。

关于c - 程序打印较晚(c),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33607783/

10-12 00:20
查看更多