
点击蓝字 关注我们

一.九九乘法表

#include <iostream>using namespace std;int main() {// 打印九九乘法表for (int i = 1; i <= 9; ++i) {for (int j = 1; j <= i; ++j) {cout << j << "*" << i << "=" << (i * j);if (j < i) {cout << "\t";}}cout << endl;}return 0;}
生成结果:
1*1=11*2=2 2*2=41*3=3 2*3=6 3*3=91*4=4 2*4=8 3*4=12 4*4=161*5=5 2*5=10 3*5=15 4*5=20 5*5=251*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=361*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=491*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=641*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
这个程序使用两个嵌套的 for 循环,外循环控制行数,内循环控制每行的列数。在内循环中,程序打印乘法表达式和结果,并在每个乘法表达式之间添加制表符,以使输出对齐。程序通过 endl 在每一行的末尾输出换行符。
二.计算器
#include <iostream>using namespace std;int main() {char operation;double operand1, operand2, result;// 用户输入运算符和操作数cout << "请输入运算符 (+, -, *, ): ";cin >> operation;cout << "请输入第一个操作数: ";cin >> operand1;cout << "请输入第二个操作数: ";cin >> operand2;// 根据用户输入的运算符执行相应的运算switch (operation) {case '+':result = operand1 + operand2;cout << "结果: " << result << endl;break;case '-':result = operand1 - operand2;cout << "结果: " << result << endl;break;case '*':result = operand1 * operand2;cout << "结果: " << result << endl;break;case '/':if (operand2 != 0) {//除数是否为0,不为0才可继续执行result = operand1 operand2;cout << "结果: " << result << endl;}else {cout << "错误:除数不能为零。" << endl;}break;default:cout << "错误:无效的运算符。" << endl;}system("pause");return 0;}
生成结果:
请输入运算符 (+, -, *, ): +请输入第一个操作数: 3请输入第二个操作数: 5结果: 8
请输入运算符 (+, -, *, ): *请输入第一个操作数: 5请输入第二个操作数: 2结果: 10
这个程序首先要求用户输入运算符和两个操作数,然后使用 switch 语句根据运算符执行相应的计算。程序还包含一些错误检查,例如检查除法时除数是否为零。
END
文章转载自Cpp入门到精通,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




