跳到正文

个人记录

c++中出现-nan(ind)的原因和辨别办法

pip202513约 5 分钟
原文
文章信息与版本

文章信息

发布
2023年10月14日
收录
2026年2月28日
更新
2026年11月7日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

nan: not a number 非数字

  1. 出现原因:

(1)分母为“0”,如果分母为零,自然时不能得到一个确定的数字的。

(2)对负数开平方、对负数求对数(log(-1.0))。注:0/0会产生操作异常;0.0/0.0不会产生操作异常,而是会得到nan。

(3)有些编译器在对无穷大与无穷小的计算时也会出现此类情况。

具体发现过程于GANG2017NOIP提高组(奶酪)时FX

C++
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
using namespace std;
int n,h,r,read(),id;
bool pre[1005],suf[1005];
vector<int> a[1005];
map<int,int> t;
//bool pre[1005],suf[1005];

inline int twice(int value) {return value*value;}

bool bfs(queue<int> q){
	bool vis[n+1];
	memset(vis,1,sizeof(vis));
	while(!q.empty())
	{
		int u=q.front();
		//cout<<q<<endl;
		q.pop();
		vis[u]=false;
		for(auto v:a[u]){
			if(t.find(v)!=t.end()) return true;
			if(vis[v]){
				q.push(v);
				vis[v]=false;
			}
		}
	}
	return false;
}

void init()
{
	//memset(dist,);
	id=0;
	queue<int> q;
	t.clear();
	cin>>n>>h>>r;
	double R=r;
	for(int i=1;i<=n;i++) a[i].clear();
	int x[n+1],y[n+1],z[n+1];
	for(int i=1;i<=n;i++) {x[i]=read(); y[i]=read(); z[i]=read();}
	for(int i=1;i<=n;i++)
	{
		long double k;
		pre[i]=(z[i]-r<=0)?1:0;
		if((z[i]>0&&(z[i]-r<=0))||(z[i]<0&&(z[i]+r>=0))||z[i]==0) q.push(i);
		suf[i]=(z[i]+r>=h)?1:0;
		if((z[i]>h&&(z[i]-r<=h))||(z[i]<h&&(z[i]+r>=h))||z[i]==h) t.insert(make_pair(i,++id));
		for(int j=i+1;j<=n;j++)
		{
			k=sqrt(twice(x[i]-x[j])+twice(y[i]-y[j])+twice(z[i]-z[j]));
			if(k<=2.0*R) a[i].push_back(j),a[j].push_back(i);
		}
 		cout<<k;
	}
	/*for(int i=1;i<=n;i++)
	{
		cout<<i<<endl;
		for(auto v:a[i]){
			cout<<v<<" ";
		}
	}

	cout<<"组:"<<t.size()<<endl;
	for(int i=1;i<=n;i++)
	{
		cout<<i<<" "<<pre[i]<<" "<<suf[i]<<endl;
		//for(int j=i+1;j<=n;j++)
		//
		//	cout<<j<<" "<<dist[i][j]<<endl;
		//
	}*/
	if(q.empty()==1){
		printf("No\n");
		return;
	}
	if(t.size()==0){
		printf("No\n");
		return;
	}
	else if(q.empty()){
		printf("No\n");
		return;
	}
	else if(n==1){
		printf("Yes\n");
		return;
	}
	else bfs(q)==1?printf("Yes\n"):printf("No\n");
	return;
}

int main()
{
	int T;
	cin>>T;
	for(int i=1;i<=T;i++) init();
	return 0;
}

int read()
{
	int x=0,f=1;
	char ch=getchar();
	while(ch>'9'||ch<'0')
	{
		if(ch=='-') f=-1;
		ch=getchar();
		}
	while(ch<='9'&&ch>='0')
	{
		x=(x<<3)+(x<<1)+ch-'0';
		ch=getchar();
		}
	return x*f;
}

/*
1
2 5100500 1275250
0 0 1275250
0 50500 3825250*/
原文