2017-05-21 15 views
2
#include <iostream> 
int main() 
{ 
    int cnt = 0, sum = 0, value = 0; 
    std::cout << "Please enter a set of numbers and then press ctrl+z and ENTER to add the numbers that you entered" << std::endl; 
    if (cnt = value) 
    ++cnt;   
    while (std::cin >> value) 

     sum += value; 

    std::cout << "the sum is: " << sum << std::endl; 
    std::cout << "the amount of numbers you entered are: " << cnt << std::endl; 

    return 0; 

} 

私が持っているifステートメントは間違っていて、ユーザーが入力する整数の数は数えません。ループを使用してユーザーが入力する整数をカウントします。

ループを使用して入力する整数の数をプログラムでカウントするにはどうすればよいですか?新しい入力が与えられるたびに

+0

あなたは、入力と出力の例 –

+1

を提供する必要がある[ツアー]をお読みください。あなたのタイトルは、単語ではなく関連性のない情報から始まります。あなたの質問に対する答えはYesです。 (これはひどく尋ねられる質問になります)。 – Anthon

+0

ところで、警告を有効にする必要があります。あなたのコンパイラはおそらく 'if(cnt = value)'について警告するでしょう。https://stackoverflow.com/questions/17681535/variable-assignment-in-if-condition – stephan

答えて

4

解決策を提供する整数の数をカウントするために

を説明し、単にCNTに1を加えます。 (下記の// **コメントの行を参照)。

また、開始時のcnt ==値チェックは不要です(そこに '='文字が1つあります)。次のようにあなたのコードを変更する必要があり、それをすべてまとめると

更新されたコード

#include <iostream> 
int main() 
{ 
    int cnt = 0, sum = 0, value = 0; 
    std::cout << "Please enter a set of numbers and then press ctrl+z and ENTER to add the numbers that you entered" << std::endl;  
    while (std::cin >> value) 
    { 
     sum += value; 
     cnt++; //** 
    } 
    std::cout << "the sum is: " << sum << std::endl; 
    std::cout << "the amount of numbers you entered are: " << cnt << std::endl; 

    return 0; 

} 
+0

ありがとうございます!!! :) – romeroj1994

関連する問題