【问题标题】:Why output is printed in asci code instead of integer ?dart为什么输出以 asci 码而不是整数打印?dart
【发布时间】:2023-04-09 16:55:02
【问题描述】:

我不知道为什么输出是ASCII码而不是整数值,我的代码有什么问题?

import 'dart:io';

void main() {
  int n = 0;
  print("input: ");

  do {
    n = stdin.readByteSync();
  } while (n>1000 || n<0);

  if (n % 4 == 0) {
    print("output: ");
    print(n);
    n++;
  } else {
    print("output: ");
    n--;
    print(n);
  }
}

【问题讨论】:

  • 你能代替截图,添加你的代码吗?

标签: console dart output flutter


【解决方案1】:

粘贴您的代码,以便更轻松地为您提供帮助。 如果你愿意,我可以给你一个固定的源代码。

相反,我将尝试解释: 您的标准输入将作为字符串提供,您将其读取为字节,因此 5 将以十六进制形式出现 35。 当您打印它时,我的猜测是它会自动转换为十进制值 (53,输出显示 52 因为53 % 4 = 1 然后在打印之前用@​​987654326@ 减少所以它变成52 )。 像您所说的ASCII Table 的那些数字。 为了修复它,请确保您具有输入 (stdin) 的字符串表示形式。然后将值转换为整数:"2".toInt()

编辑: 我可以很容易地找到完整的解决方案, 您需要先将 stdin 作为字符串获取:readLineSync 并将其转换为 int:

n = int.parse(stdin.readLineSync());

注意:代码未经测试,但非常简单。

【讨论】:

  • String 没有toInt(),而是使用int.parse()
【解决方案2】:

使用stdin.readLineSync() 获取String 的值,然后将parse 获取为int,如下所示:

import 'dart:io';

void main() {
  int n = 0;
  print("input: ");

  do {
    n = int.parse(stdin.readLineSync());
  } while (n>1000 || n<0);

  if (n % 4 == 0) {
    print("output: ");
    print(n);
    n++;
  } else {
    print("output: ");
    n--;
    print(n);
  }
}

【讨论】:

  • 使用 int.parse 后输出正确显示。谢谢您的解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2021-12-22
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
相关资源
最近更新 更多