两个数字a和b的相乘得到它们的乘积。将a的值与b的值相加多次,以获得a和b的乘积。
例如。
5 * 4 = 20 7 * 8 = 56 9 * 9 = 81
使用*运算符将两个数字相乘的程序如下所示-
#include <iostream> using namespace std; int main() { int a = 6, b = 8; cout<<"Product of "<<a<<" and "<<b<<" is "<<a*b<<endl; return 0; }
输出结果
Product of 6 and 8 is 48
在上面的程序中,使用*运算符简单地显示a和b的乘积。下面的代码段对此进行了演示。
cout<<"Product of "<<a<<" and "<<b<<" is "<<a*b<<endl;
给出一个不使用*运算符将两个数字相乘的程序,如下所示:
#include<iostream> using namespace std; int main() { int a=7, b=8, product=0; for(int i=1; i<=b; i++) product = product + a; cout<<"The product of "<<a<<" and "<<b<<" is "<<product<<endl; return 0; }
输出结果
The product of 7 and 8 is 56
在上面的程序中,一个for循环用于将总共b次的值相加。这产生a和b的乘积。
下面的代码段对此进行了演示。
for(int i=1; i<=b; i++) product = product + a;
此后,显示a和b的乘积。这显示如下-
cout<<"The product of "<<a<<" and "<<b<<" is "<<product<<endl;