我一直難以將一段在 Pascal 中運行的代碼復制到 dart 中。該程式要求輸入、添加兩支球隊的分數,并在最后顯示總分。我設法獲得所有輸入和輸出,但 for 回圈中的加法輸出 0 或 null。有什么建議嗎?
import "dart:io";
import "dart:math";
import "dart:convert";
void main() {
double pscore1 = 0;
double Totscore1 = 0;
print('Enter enter team 1 name');
String? Team_one_Name = stdin.readLineSync();
print('Enter enter team 2 name');
String? Team_two_Name = stdin.readLineSync();
for (int i = 0; i < 5; i ) {
print('Enter team 1 player score');
double pscore1 = double.parse(stdin.readLineSync()!);
double Totscore1 = (Totscore1 pscore1);
}
print(' The total score is ${Totscore1}');
}
這只是一個分數。提前致謝。
uj5u.com熱心網友回復:
您在for回圈中宣告新變數,而不是使用main()方法中定義的變數。由于您的新變數命名相同,它們將“隱藏”您的其他變數,因為 Dart 的作用域規則意味著當我們參考某些東西時,我們從當前作用域開始搜索,然后一次上升一級,直到我們到達全域作用域:
相反,請嘗試執行以下操作:
import "dart:io";
import "dart:math";
import "dart:convert";
void main() {
double pscore1 = 0;
double totscore1 = 0;
print('Enter enter team 1 name');
String? Team_one_Name = stdin.readLineSync();
print('Enter enter team 2 name');
String? Team_two_Name = stdin.readLineSync();
for (int i = 0; i < 5; i ) {
print('Enter team 1 player score');
pscore1 = double.parse(stdin.readLineSync()!);
totscore1 = totscore1 pscore1;
}
print(' The total score is ${totscore1}');
}
(我將你重命名為Totscore1,totscore1因為如果我們遵循正常的命名約定,變數在 Dart 中永遠不應該以大寫字母開頭)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/511982.html
