C++用户输入、判断语句和switch的使用方法

发布时间:2021-06-15 16:13:06 作者:chen
来源:亿速云 阅读:280

这篇文章主要讲解了“C++用户输入、判断语句和switch的使用方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++用户输入、判断语句和switch的使用方法”吧!

用户输入

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

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

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

#include <iostream>  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 }

 C++用户输入、判断语句和switch的使用方法

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

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

公式如下:

C++用户输入、判断语句和switch的使用方法

#include <iostream> 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"; }

 C++用户输入、判断语句和switch的使用方法

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

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

#include <iostream>  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"; }

 C++用户输入、判断语句和switch的使用方法

判断语句

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

#include <iostream>  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 <iostream>  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 <iostream>  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的使用方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. PowerShell Switch判断语句示例
  2. C++中怎么使用switch语句

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++ switch

上一篇:Python中怎么实现切片操作

下一篇:使用TensorFlow怎么合并或连接数组

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》