400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

C++用户输入、判断语句和switch怎么使用

本文小编为大家详细介绍“C++用户输入、判断语句和switch怎么使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“C++用户输入、判断语句和switch怎么使用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

成都创新互联长期为上千多家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为宁强企业提供专业的网站制作、成都网站设计,宁强网站改版等技术服务。拥有十多年丰富建站经验和众多成功案例,为您定制开发。

用户输入

cout用于输出(打印)值的 。现在将使用cin来获取用户输入。

cin是预定义的变量,可使用提取操作符(>>)从键盘读取数据。

在下面的示例中,用户可以输入一个数字,该数字存储在变量中x。然后我们输出的值x:

#include   using namespace std;  int main(){     int x = 0;     cout << "Type a number: "; // Type a number and press enter     cin >> x; // Get user input from the keyboard     cout << "Your number is: " << x; // Display the input value }

最近,Kelvin 开始在他的网站上发布他的天气预报,但是,有一个问题:他的所有预测都以华氏度来描述温度。

让我们将温度从华氏 F转换为摄氏 C

#include  int main() {      double tempf;   double tempc;   // Ask the user   std::cout << "Enter the temperature in Fahrenheit: ";   std::cin >> tempf;    tempc = (tempf - 32) / 1.8;   std::cout << "The temp is " << tempc << " degrees Celsius.\n"; }

计算身体质量指数。身体质量指数(BMI)是常用的健康和营养专家估计在人群人体脂肪。

它的计算方法是将个人的体重(公斤)除以身高(米)的平方(m²)

#include   int main() {   double height, weight, bmi;   // Ask user for their height,weight   std::cout << "Type in your height (m): ";   std::cin >> height;   std::cout << "Type in your weight (kg): ";   std::cin >> weight;   // Now ask the user for their weight and calculate BMI   bmi = weight / (height * height);   std::cout << "Your BMI is " << bmi << "\n"; }

判断语句

一个if语句用于测试真理的表达和执行基于它的一些代码。这是该if语句的一种简单形式:

#include   int main() {     int x = 20;     int y = 18;     if (x > y)     {         std::cout << "x is greater than y";     }     else     {         std::cout << "y is greater than x";     } }

在化学中,pH是用于指定水溶液的酸度或碱度的标度。

写一个if,else if,else语句:

#include   int main() {      double ph = 4.6;      if (ph > 7)     {          std::cout << "Basic\n";     }     else if (ph < 7)     {          std::cout << "Acidic\n";     }     else     {          std::cout << "Neutral\n";     } }

switch

#include   int main() {      int grade = 9;     switch (grade)     {     case 9:         std::cout << "Freshman\n";         break;     case 10:         std::cout << "Sophomore\n";         break;     case 11:         std::cout << "Junior\n";         break;     case 12:         std::cout << "Senior\n";         break;     default:         std::cout << "Invalid\n";         break;     } }

读到这里,这篇“C++用户输入、判断语句和switch怎么使用”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注创新互联行业资讯频道。


网页名称:C++用户输入、判断语句和switch怎么使用
分享URL:http://mbwzsj.com/article/iidiec.html

其他资讯

让你的专属顾问为你服务