第一章 C++ 我来了——1.3 关于注释 & 1.4 While, For and If

本文详细介绍了C++中的注释用法及while、for、if等控制结构的应用,并通过实例展示了如何利用这些控制结构实现基本的数据处理任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.3 注释


注释嘛咱就不多说了,照着葫芦画瓢吧!喏,葫芦就在下面:

#include <iostream>
/* I am block comments
 * The soft engineers like to employ the "*" as the head of the line to indicate 
 * this line is still a part of the block comments
 */ 

int main()
{
  //I am single line comments, I can only protect the content in this line
  return 0;
}

1.4 While, For and If


1.4.1 While

while (condition) while_body-statement;
#include <iostream>

int main ()
{
  int sum = 0, val = 1;

  while (val <= 10)
  {
    sum += val;
    ++val;
  }

  std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
  return 0;
}

Tips:

  • 在使用控制结构进行迭代时,总会需要对condition进行判断。如果condition为真时,则执行while_body_statement。请注意,表达式求值不为0时,conditionTRUE

1.4.2 For


#include <iostream>

int main ()
{
  int sum = 0;

  for (int val = 0; val <= 10; ++val)
    sum += val;

  std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
  return 0;
}

1.4.3 If


#include <iostream>
//Calculate the sum of the numbers between v1 and v2
int main ()
{
    std::cout << "Enter two numbers: " <<std::endl;
    int v1, v2;
    std::cin >> v1 >> v2;

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

    int sum = 0;
    for (int i = lower; i <= upper; ++i){
        sum += i;
    }       
    std::cout << sum <<std::endl;

    return 0;
}

1.4.4 读入未知数目的输入


OK,终于有点新东西了,看,那个人好像条狗啊!

#include <iostream>

int main ()
{
    int cout = 0, value;

    while(std::cin >> value){
        if(value < 0){
            ++cout;
        }
    }
    std::cout << cout <<std::endl;

    return 0;
}

Tips:

在使用std::cin >> value进行判断时,有两种情况可以终止循环。

  • 遇到文件结束符(end-of-file)。不同的操作系统使用不同的值作为文件结束符,Windows系统使用同时键入ctrlz作为文件结束符;Unix系统下则使用control-d
  • 遇到无效输入。如上述code我们输入非整数值。
  • 注意:上述code在使用非整数负数进行结束时,该负数会被计入cout变量。

Postscript:

关于本章1.51.6两个关于的简介,就不再继续展开了,在以后的章节中具体学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值