最近我写了一段代码:
const int sections = 10;
for(int t= 0; t < 5; t++){
int i = pow(sections, 5- t -1);
cout << i << endl;
}
Run Code Online (Sandbox Code Playgroud)
结果是错误的:
9999
1000
99
10
1
Run Code Online (Sandbox Code Playgroud)
如果我只使用这个代码:
for(int t = 0; t < 5; t++){
cout << pow(sections,5-t-1) << endl;
}
Run Code Online (Sandbox Code Playgroud)
问题不再发生:
10000
1000
100
10
1
Run Code Online (Sandbox Code Playgroud)
有没有人给我解释?非常感谢你!
这个打印100:
int j=2;
int i= pow(10,2);
printf("%d\n", i);
Run Code Online (Sandbox Code Playgroud)
这个打印99:
int j=2;
int i= pow(10,j);
printf("%d\n", i);
Run Code Online (Sandbox Code Playgroud)
为什么?
#include <iostream.h>
#include <math.h>
int main()
{
int j=2;
int output;
output=pow(10,j);
cout<<output;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我把上面的代码写到gcc 12编译器,得到输出99而不是100.我在搜索各种网站时没有得到正确的理由.有编译器问题吗?
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main(int argc, char **argv)
{
string c;
int k = 0, decval, i;
cout << "Please input your number starting from lowest value number to highest" << endl;
cin >> c;
//the for loop takes a backwards integer and makes it forwards.
for(i = 0; i < c.length(); i++){
decval += (c[i] - '0') * pow(10, k);
++k;
}
cout << decval;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是当我输入像564这样的东西(想得到465作为回报)我得到462.我无法在代码中发现逻辑错误.请注意,我是编码和堆栈溢出的新手,所以请不要太苛刻.任何帮助将不胜感激.