You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart使用条件语句开发答题应用时实现总分累加计算

Dart控制台答题应用总分计算实现方案

要实现得分累加、最终总分输出的功能,只需要在判分逻辑前初始化一个初始值为0的总分变量,每道题判定回答正确时就将对应单题得分累加到该变量上,所有题目判分完成后统一输出总分即可。
原代码存在几个可优化的小问题,修改时一并修复:

  • 冗余导入dart:math、定义后从未使用的num3变量可以直接删除
  • 第4题正确答案定义为小写no,但给用户展示的选项为首字母大写No,直接对比会导致用户输入符合展示规则的内容时被误判,对比前统一对字符串类型的用户输入做去空格、转小写处理即可
  • 固定的单题分值可以抽为常量,后续调整分值时只需要修改一处

修改后可直接运行的完整代码
import 'dart:io';

void main() {
  print("Hi, welcome to quize app");
  print("what is your name?");
  String? username = stdin.readLineSync();
  print("welcome ${username}");
  
  // 初始化总分容器,初始值为0
  int totalScore = 0;
  // 单题固定得分
  const int perQuestionScore = 10;

  print("Who is Christiano ronaldo?");
  List answers1 = [26, 30, 37, 36];
  List answers2 = ['Musician', 'Footballer', 'Swimmer'];
  List answers3 = [3, 5, 7, 17];
  List answers4 = ['Yes', 'No'];

  int ans1 = 36;
  String ans2 = 'footballer';
  int ans3 = 17;
  String ans4 = 'no';

  print(answers1);
  int userans1 = int.parse(stdin.readLineSync()!);
  print("Who the next president of Nigeria?");
  print(answers2);
  // 处理用户输入:去前后空格、转小写,避免误判
  String? userans2 = stdin.readLineSync()?.trim().toLowerCase();
  print("How many times did national Grid collaps in 2022 alone? please type in numbers:");
  print(answers3);
  int userans3 = int.parse(stdin.readLineSync()!);
  print('Is Nigerian air still functioning?');
  print(answers4);
  String? userans4 = stdin.readLineSync()?.trim().toLowerCase();

  print('end of quize');
  print('calculating answers...');

  // 第一题判分
  if (userans1 == ans1) {
    totalScore += perQuestionScore;
    print("In question number one (1) you got $perQuestionScore");
  } else {
    print("In question number one (1) you got 0");
  }

  // 第二题判分
  if (userans2 == ans2) {
    totalScore += perQuestionScore;
    print("In question Number two (2) you got $perQuestionScore");
  } else {
    print("In question Number two (2) you got 0");
  }

  // 第三题判分
  if (userans3 == ans3) {
    totalScore += perQuestionScore;
    print("In question Number three (3) you got $perQuestionScore");
  } else {
    print("In question Number three (3) you got 0");
  }

  // 第四题判分
  if (userans4 == ans4) {
    totalScore += perQuestionScore;
    print("In question Number four (4) you got $perQuestionScore");
  } else {
    print("In question Number four (4) you got 0");
  }

  // 输出最终总分
  print("==============================");
  print("Quiz finished! Your total score is: $totalScore / ${perQuestionScore * 4}");
}

核心修改点说明
  • 新增totalScore变量作为总分累加容器,初始值设为0
  • 每道题判定回答正确时,执行totalScore += perQuestionScore完成得分累加
  • 统一字符串类答案的对比逻辑,自动处理用户输入的多余空格、大小写差异,降低误判概率
  • 清理冗余导入、无用变量,将固定单题分值抽为常量,降低后续维护成本
  • 所有题目判分完成后,格式化输出最终得分和满分值,展示效果更清晰

内容的提问来源于stack exchange,提问作者Onyeka Franklin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 08:39:15