关于2的次方运算
笔者给出了两种最基本的C语言方法
第一种是使用for循环语句
#include"pch.h"
#include <stdio.h>
/* function main begins program execution */
int main(void)
{
int pro=1;
int number;/* initialization */
int x;
printf("Please write the power:");
scanf_s("%d", &x);
for (number = 1; number <= x; number += 1) {
pro *=2 ;
}
printf("Product is %d\n", pro);
return 0; /* indicate program ended successfully */
} /* end function main */
第二种方法是利用while语句
大体思想和for语句是差不多的
#include "pch.h"
#include <iostream>
/* function main begins program execution*/
int main(void)
{
int counter = 1;
int pro=1;
int x; /*initialization*/
printf("Please write the power:");
scanf_s("%d", &x);
while (counter <= x){
pro *= 2;
counter += 1;
}
printf("Product is :%d", pro);
return 0;
}/* end function main*/
PS:
但是笔者进行了测试,
x为30的时候 积是1073741824
x为31的时候 积是-2147483648
x为32的时候 积就超过了能显示的最大极限,显示为0