【问题标题】:Why won't this let me scan in my find and then unknown?为什么这不能让我扫描我的发现然后未知?
【发布时间】:2015-07-08 12:10:34
【问题描述】:

所以,我正在尝试制作一个 suvat 求解器(物理方程),我需要阅读他们需要查找(查找)的内容以及他们不知道和不需要知道的内容(未知)。它在查找中进行扫描,但在询问未知数之前直接跳到询问变量。为什么?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main (int argc, char *argv[]) {
printf ("What are you trying to find:\nDistance, Inital Velocity, Final Velocity, Accelartion or Time\n(Enter first letter)\n");
char find;
scanf("%c", &find);
char unknown;
printf ("What don't you know: \n");
scanf("%c", &unknown);


int i = 0; //initial velocity
int f = 0; //final velocity
int a = 0; //accelaration
int t = 0; //time
int d = 0; //distance

if (((find != 'i') && (find != 'I')) && ((unknown != 'i') && (unknown != 'I'))){
    printf("What is the Inital Velocity: \n");
    scanf("%d", &i);
}
if (((find != 'd') && (find != 'D')) && ((unknown != 'd') && (unknown != 'D'))){
    printf("What is the Distance: \n");
    scanf("%d", &d);
}
if (((find != 'f') && (find != 'F')) && ((unknown != 'f') && (unknown != 'F'))){
    printf("What is the Final Velocity: \n");
    scanf("%d", &f);
}
if (((find != 'a') && (find != 'A')) && ((unknown != 'a') && (unknown != 'A'))){
    printf("What is the Accelartion: \n");
    scanf("%d", &a);
}
if (((find != 't') && (find != 'T')) && ((unknown != 't') && (unknown != 'T'))){
    printf("What is the Time: \n");
    scanf("%d", &t);
}
//printf("find: %c, i: %d, f: %d, a: %d, d: %d, t: %d", find, i, f, a, d, t);
if ((find == 'i') || (find == 'I')) {
    if ((unknown == 's') || (unknown == 'S')) {
        i = a*t - f;
        printf("%d\n", i);
    }
    else if ((unknown == 'a') || (unknown == 'A')) {
        i = ((2*d)/t) - f; 
        printf("%d\n", i);
    }
    else if ((unknown == 't') || (unknown == 'T')) {
        i = sqrt(pow(f,2)-(2*a*d)); 
        printf("%d\n", i);
    }
    else if ((unknown == 'f') || (unknown == 'F')) {
        i = (d - (0.5*a*pow(t,2)))/t;
        printf("%d\n", i);
    }
}




return EXIT_SUCCESS;
}

【问题讨论】:

  • 使用getchar() 而不是scanf()
  • @Prera​​kSola,为什么?这不会解决问题。
  • @Prera​​kSola 更糟糕的是,如果没有第二次调用 getchar() 就无法跳过回车键,而且它取决于平台

标签: c char newline scanf


【解决方案1】:
scanf("%c", &find);

应该是

scanf(" %c", &find);
   //  ^ space

在您的程序中,scanf 从您的 enter 按键中获取 \n 作为第二个字符

【讨论】:

    【解决方案2】:

    发生这种情况是因为,在第一个 scanf() 存储在输入缓冲区中后,ENTER 键按下 [a \n] 并为[下]scanf().

    在你的代码中,你需要改变

    scanf("%c", &unknown);
    

    scanf(" %c", &unknown);    
           ^
           |
         notice here
    

    这将忽略所有类似空格的输入(包括\n)并读取第一个非空格字符(即预期的输入)。

    建议:

    1. 如果您不打算使用argcargv,建议main() 的siganute 是int main(void)

    2. 您应该使用switch 大小写而不是延长的if-else if-else 条件链。

    【讨论】:

    • 使用 scanf 或 getchar() 会更好吗?
    猜你喜欢
    • 1970-01-01
    • 2015-01-19
    • 2021-11-11
    • 2018-10-31
    • 1970-01-01
    • 2017-12-16
    • 2013-09-30
    • 2020-12-23
    • 1970-01-01
    相关资源
    最近更新 更多