我正在使用C(不是C++).
我需要将一个浮点数转换成一个int.我不想舍入到最接近的数字,我只是想消除整数部分之后的内容.就像是
4.9 -> 4.9-> 4
最近我写了一段代码:
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)
有没有人给我解释?非常感谢你!
所以我参加了计算竞赛,我发现了一个奇怪的错误.pow(26,2)将总是返回675,有时是674?即使正确的答案是676.这些错误也发生在pow(26,3),pow(26,4)等比赛后经过一些调试后我相信答案与int事实有关.有趣的是,此类错误以前从未发生过.我用的电脑正在Windows 8上运行.GCC版本相当新,我相信2-3个月大.但我发现如果我在这些错误上转动o1/o2/o3优化标志会奇迹般地消失.pow(26,2)总会得到676也就是正确的答案谁能解释为什么?
#include <cmath>
#include <iostream>
using namespace std;
int main() {
cout<<pow(26,2)<<endl;
cout<<int(pow(26,2))<<endl;
}
Run Code Online (Sandbox Code Playgroud)
双打的结果很奇怪.
double a=26;
double b=2;
cout<<int(pow(a,b))<<endl; #outputs 675
cout<<int(pow(26.0,2.0))<<endl; # outputs 676
cout<<int(pow(26*1.00,2*1.00))<<endl; # outputs 676
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)
为什么?
我尝试编写一个函数将一串数字转换为整数。当我使用 g++ 9.2.0 在 VS 代码上运行我的代码时,我得到了错误的输出,但是当我在 repl.it 上运行它时,我得到了正确的输出。这是我的代码:
#include <iostream>
#include <cmath>
using namespace std;
int charToInt(char c)
{
return c - '0';
}
int myStoi(string s)
{
int r = 0, len = s.length();
for (int i = 0; i < len; i++)
{
r += charToInt(s[i]) * pow(10, len - i - 1);
}
return r;
}
int main()
{
string str = "123";
cout << stoi(str) << endl;
cout << myStoi(str) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是 …
#include <stdio.h>
int main (void)
{
int x = 10^2;
long a = 4000465006540123; //(16 places)
long b = 4000465006540123 % x;
printf("%li\n", b);
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码时(它正确编译),代码打印出“3”。难道它不应该打印出“23”,因为 x 是 100,而不是 10?