11. double 数值的整数次方
note: 浮点数表示时有误差,判等时必须自己根据精度要求实现。
#include <iostream> #include <ctime> using namespace std; bool Power_Input_Invalid = false; // set a Global variant to check the input. bool equal(double num1, double num2) // key 1 { if(num1 - num2 >= -0.0000001 && num1 - num2 <= 0.0000001) return true; return false; } double Power(double base, int exponent) { Power_Input_Invalid = false; if(equal(base,0.0) && exponent <= 0) /* 无意义 */ { Power_Input_Invalid = true; return 0.0; } if(exponent == 0) return 1.0; bool sigmal = false; // 0 denote positive exp bool overflow = false; if(exponent < 0) { if(exponent == INT_MIN) { overflow = true; exponent++;} exponent *= -1; sigmal = true; // 1 denote negative exp } double result = base, tem = 1.0; while(exponent - 1 != 0) // key 2 { if(exponent & 1) tem *= result; result *= result; exponent >>= 1; } result *= tem; if(overflow) result *= base; if(sigmal) result = 1.0 / result; return result; } int main() { double d; int v; clock_t start; int k = 0; while(cin >> d >> v) { start = clock(); double result = Power(d, v); if(!Power_Input_Invalid) cout << "Case " << k++ << ": " << Power(d, v) << " time:" << (clock()-start) << "ms" << endl; else cout << "Invalid input." << endl; } return 0; }
12.打印 1 到最大的 n 位数
note: n 可能很大,如 100,就容易溢出
a. 字符串模拟法
1 #include <stdio.h> 2 #include <string.h> 3 bool Increment(char *); 4 void printNumber(char *); 5 6 void print1ToMax(int n) 7 { 8 if(n <= 0) return; 9 char *number = new char[n+1]; 10 memset(number, '0', n); 11 number[n] = '