【问题标题】:Having difficulty correctly inputting multiple integers at the same time using scanf()使用 scanf() 难以同时正确输入多个整数
【发布时间】:2021-09-16 18:33:23
【问题描述】:

所以我有一个编码项目,我必须计算一个学生在班级中的总成绩,他们有 4 次测验、2 次期中考试和 1 次期末考试。测验和考试权重为 30%,期中考试权重为 40%。我只帮忙做两件事:

  1. 我的代码不想在没有 4 个单独的输入数字 (79 80 0 0) 的情况下开始。
  2. 当进入代码的考试部分时,由于某种原因,它会绕过所需的用户输入并将其自动转换为测验编码中的第三个数字。 我正在编写 c 编程。
#include <stdio.h>

int main()
{
    int testOne, testTwo;
    float totTest, percTest, testPoint;
    printf("Enter you test grades:\n");
    scanf("%d%d\n",&testOne,&testTwo);
    totTest=testOne+testTwo;
    printf("Your total grade points is: %.1f\n", totTest);
    testPoint=200;
    percTest=(totTest*.40)/testPoint *100;
    printf("Your percentage is %.1f%\n", percTest);
    
    int quizOne, quizTwo, quizThree, quizFour;
    float totQuiz, percQuiz, quizPoint;
    printf("Enter you quiz grades:\n");
    scanf("%d%d%d%d\n", &quizOne, &quizTwo, &quizThree, &quizFour);
    totQuiz=quizOne+quizTwo+quizThree+quizFour;
    printf("Your total quiz grade is %.1f\n", totQuiz);
    quizPoint=400;
    percQuiz=(totQuiz*.30)/quizPoint *100;
    printf("Your quiz percentage is %.1f%\n", percQuiz);
    
    int examOne, examPoint; <This is the code that automatically messes up>
    float percExam, finGrade;
    printf("Enter your exam grade\n");
    scanf(" %d\n", &examOne);
    examPoint=100;
    percExam=(examOne*.30)/examPoint *100;
    printf("Your final exam grade is %.1f\n", percExam);
    finGrade=(percExam+percQuiz+percTest);
    printf("Your overall grade is %.1f%\n", finGrade);
    
    return 0;
}

【问题讨论】:

标签: c


【解决方案1】:

您的问题与您的程序逻辑无关,与计算成绩无关,与:scanf 有关。在介绍 C 编程时,scanf 同时是 C 库中看起来最有用但实际上最无用的函数。

以下是在介绍性 C 编程中使用 scanf 的三个简单规则:

  1. 使用以下四种输入格式之一:"%d""%s""%f""%lf"。如果您只是必须阅读单个字符,则可以添加第五个:" %c"(但请确保始终使用额外的空间)。单独使用这些,一次一个,不要组合它们或添加任何其他字符。

  2. 始终检查scanf 的返回值。如果不返回 1,则打印错误信息并退出:if(scanf(...) != 1) {printf("input error!\n"); exit(1); }

  3. 如果你想做一些更奇特的事情,而规则 1 允许的有限格式数量无法完成,那么是时候learn how to use something better than scanf了。

特别是,不要尝试使用%d%d 等格式一次读取多个数字。也不要在 scanf 格式的语句中使用\n——它不会按照你的想法做,它可能会给你带来问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2015-12-15
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多