輸入一組數,輸出其中有多少個負數。

來源:互聯網
上載者:User

1.輸入一組數,輸出其中有多少個負數。

 

程式碼如下:

#include <iostream>

int main()
{
 int sum = 0, value;
 
 std::cout << "Please input your numbers [End with CRTL+D] :" << std::endl;
 while (std::cin >> value) {
  if (value < 0) {
   sum++;
  }
 }

 std::cout << "There is " << sum << " negative numbers ." << std::endl;

 return 0;
}

 

2. 提示使用者輸入兩個數,並將這兩個數之間的每個數輸出。

 

程式碼如下:

#include <iostream>

int main()
{
 int v1, v2;
 std::cout << "Please input v1 and v2 : " << std::endl;
 std::cin >> v1 >> v2 ;
 std::cout << "The number between the " << v1 << " and " << v2 << std::endl;
 
 int lower, upper;
 if (v1 <=v2) {
  lower = v1;
  upper = v2;
 } else {
  lower = v2;
  upper = v1;
 }

 int value = lower;
 while (value < upper-1) {
  ++value;
  std::cout << value << " ";
 }

 return 0;
}

 

3.輸入兩個數,再求兩個數之間的數之和

 

程式碼如下:

#include <iostream>

int main()
{
 int v1, v2;

 std::cout << "Please input v1 and v2 :" << std::endl;
 std::cin >> v1 >> v2;

 int upper, lower;
 if ( v1 <= v2) {
  upper = v2;
  lower = v1;
 } else {
  upper = v1;
  lower = v2;
 }

 int sum = 0;
 for (int i = lower+1; i <= upper-1; i++) {
  sum +=i;
 }
 std::cout << "The sum of the numbers between " << v1 << " and " << v2 << " is " << sum <<std::endl;
 return 0;
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.