私はイントロをプログラミングクラスに書くためのアプリケーションを書いています。 キーボードを使用して50から100までの正の整数を入力するようにユーザーに促す簡単なプログラムを設定します。プロンプトは、入力プロセスを停止するために、ユーザーに負の数を入力するように指示する必要があります。
ユーザーが数字を入力すると、有効な入力の数(許可された範囲内の数字)を記録し、それらの数字のエントリを追加する必要があります。入力した1つの数値、数、および現在計算している合計数を超える値を格納する必要はありません。
ユーザーがデータ入力を完了すると、次のような出力が生成されます。
A total of 5 values were entered.
The sum of those numbers is 127
1つの変数を持つプログラムを作成し、ユーザーを取得します
ここに私が書いたコードです
#include
#include
using namespace std;
int main(int argc, char *argv[]) {
int loop = 1;
int value;
int times = 0;
cout << "Enter a negavtive number to quit" << endl;
cout << "\nPlease Enter Any Number Between 50 - 100" << endl;
while (loop == 1) {
cin >> value;
times++;
value += value;
if(value < 0) {
cout << "You entered " << times - 1 << " numbers" << endl;
cout << "Total: " << value << endl;
system("PUASE");
return EXIT_SUCCESS;
}// end if statement
} //end while loop
system("PAUSE");
return EXIT_SUCCESS;
}
Here is the output http://www.flickr.com/photos/[email protected]/6286454476/
私は、int値を使って2つの異なるタスクを実行しているという事実とは関係があると思います。 これを修正するにはどうすればいいですか?
thanks to all of you for the "fix" I add a new variable and it works like a charm, but now the math is not adding correctly http://www.flickr.com/photos/[email protected]/6286526294/in/photostream
いくつかの問題がありますが、主なものは次のとおりです。
cin >> value;
これは、 " value
をユーザーが入力した数値で上書きする"ことを意味します。上書きするため、値を value
に保存することはできません。毎回新しい番号で
解決策:別の変数を使用して、実行中の合計を保持します。
あなたはまたあなたがしていることにバグがあります
times++;
value += value;//which as described above will not "stick"
before checking if value
is negative. These operations should only be performed when value
is not negative; otherwise, data entry should stop immediately and the negative number should not be taken into account for summing the total.