当前位置:首页 > 应用开发

详解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 } 

 

cout发音为“see-out”。用于输出,断语并使用插入运算符(<<) cin发音为“ see-in”。句和用于输入,详解并使用提取运算符(>>)

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

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

公式如下:

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

 

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

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

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

 

判断语句

一个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语句:

如果ph大于 7,则输出“Basic”。 如果ph小于7,则输出“ Acidic”。 如果两者都不是,则输出“中性”。 #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;     } }  该switch关键字发起声明,其次是(),它包含了各种情况下将比较值。在示例中,switch 语句的值或表达式为grade。云南idc服务商在此表达一个限制是它必须评估为整型(int,char,short,long,long long,或enum)。 在块内部{ },有多种情况。 case关键字检查是否表达后它附带指定值相匹配。第一种情况后的值为9。如果 的值grade等于9,:则将运行后面的代码。 该break关键字告诉计算机退出块,不再执行任何代码或检查代码块内的任何其他情况。 在每个 switch 语句的末尾,都有一个default语句。如果所有情况都不是true,则default语句中的代码将运行。它本质上是else一部分。云服务器

分享到:

滇ICP备2023006006号-16