[英]An error with Floating Point Exception C++ expression
我是C ++的初學者,嘗試獲取110之類的數字。我嘗試了以下代碼,但出現了Floating Point Exception C ++錯誤。 我不明白哪里出了問題。
int main()
{
int p = 10;
int j = 1;
while(110 % p >=1 || 110 % p ==0){
cout<<110 % p;
j++;
p = p *10;
}
}
任何人都可以更正代碼嗎?
您的問題是模數是余數,如果您從數學角度考慮正在做的事情是沒有意義的。 當您將一個數字除以另一個數字時,有余數或沒有余數。 只要有剩余或沒有剩余,您就將繼續循環。 這導致p上出現整數溢出。
嘗試這個:
#include <iostream>
using namespace::std;
int main()
{
// this prints out the digits backwards:
for(int InitialNumber=110;InitialNumber!=0;InitialNumber/=10){
int LastDigit=InitialNumber%10;
cout<<LastDigit<<endl;
}
return 0;
}
輸出:
martyn@localhost ~ $ g++ test.cpp -std=c++11
martyn@localhost ~ $ ./a.out
0
1
1
如果您堅持使用算法,則可以這樣終止它:
int main()
{
int p = 10;
int j = 1;
while( p < 110*10 ){
cout<<110 % p<<endl;
j++;
p = p *10;
}
}
這將使循環永遠停止並溢出P。這將為您提供:
martyn@localhost ~ $ ./a.out
0
10
110
我懷疑不是您想要的,而是只想要第一個數字,因此您需要將輸出除以十的前次冪,如下所示:
int main()
{
int p = 10;
while( p < 110*10 ){
cout<<(110 % p)/(p/10)<<endl;
p = p * 10;
}
}
那會給你:
martyn@localhost ~ $ g++ test.cpp -std=c++11
martyn@localhost ~ $ ./a.out
0
1
1
但是我懷疑第一個代碼摘錄更優雅。 請注意,在所有這些示例中,數字都是從背面打印出來的。 這可能不是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.