实验目的:
掌握逻辑表达式的使用方法。掌握if和switch语句的使用方法。掌握一些简单的算法。实验内容:
#include <iostream> using namespace std; int main() { cout << "1、根据输入的x输出y:" << endl; int x, y; cout << "请输入x:"; cin >> x; if (x < 1) y = x; else if (1 <= x && x < 10) y = 2 * x - 1; else y = 3 * x - 11; cout << "y=" << y << endl; cout << endl; cout << "2、判断是否为素数:" << endl; int number; bool prime = true; cout << "输入数字:"; cin >> number; for (int i = 1; i <= sqrt(number); i++) { if (number % i == 0 && i != 1) { prime = false; break; } } if (prime) cout << number << " is a prime number." << endl; else cout << number << " is not a prime number." << endl; cout << endl; cout << "3、输入0到100分,转化为五级制:" << endl; while (1) { int score; cout << "分数="; cin >> score; if (score < 0) { cout << "分数小于0,非法!" << endl; continue; } if (score > 100) { cout << "分数大于100,非法!" << endl; continue; } else { cout << "等级="; switch (score/20) { case 0: cout << "E" << endl; case 1: cout << "D" << endl; case 2: cout << "C" << endl; case 3: cout << "B" << endl; default: cout << "A" << endl; } break; } } }注意:case后不能跟>=这样的符号,所以把score/20,在int条件下就只有0,1,2,3,4,5这几种情况了,也就可以达到我们的目的了