[英]Why do I get error “'cout' in namespace 'std' does not name a type” when I use “using cout = std::cout;”?
[英]Why do i get "-inf" instead of the typed cout in if
問題是確定方程 a*x+b=0 是否有 1 個解,並寫下它,如果它有 0 個解,則寫無解,如果它有無限解,則寫出無限解
#include <iostream>
using namespace std;
int main()
{
float a,b,x;
cin>>a>>b;
x=-b/a;
if(x!=0)
cout<<x<<endl;
else if(a==0)
cout<<"no solution"<<endl;
else
cout<<"infinite solutions"<<endl;
return 0;
}
它應該寫“無解決方案”,但它說 -inf
您的支票順序錯誤。 由於您沒有指定輸入,我的假設是:
a=0;
b=1; // Or any other number, for that matter
這意味着,對於您的輸入,您將-1
除以0
,即-inf
(數學上不正確,但浮點數(有時)以這種方式工作,請參閱The behavior of floating point division by zero )
If-else 鏈從上到下評估,在評估為true
的第一個條件處停止。
當您首先檢查x!=0
並且-inf
不等於0
時,您只會得到-inf
的輸出。
為確保您捕捉到被零除的情況,您需要先檢查一下。
你的代碼看起來像這樣:
#include <iostream>
using namespace std;
int main()
{
float a,b,x;
cin>>a>>b;
x=-b/a;
if(a==0)
cout<<"no solution"<<endl;
else if(x!=0)
cout<<x<<endl;
else
cout<<"infinite solutions"<<endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.