Why do I get NaN values ​​in this code?

I welcome you.
Why do I get NaN values ​​in this code when I press the A button twice?
Here’s the code:

using UnityEngine;
using System.Collections;

public class EszrevetelScript: MonoBehaviour {
	
	private Transform other;
	private Quaternion toRotate;
	private Vector3 distance, tempVec;
	private float szog, cos, rad, speed = 0.05f;
	
	// Use this for initialization
	void Start () {
	    other = GameObject.Find ("CylinderTwo").transform;
		toRotate = Quaternion.identity;
	}
	
	// Update is called once per frame
	void Update () {
	    if(Input.GetKeyDown(KeyCode.A))
		{
			distance = other.transform.position - transform.position;
			distance.Normalize();
			cos = Vector3.Dot (transform.forward, distance);
			rad = Mathf.Acos(cos);
			szog = Mathf.Rad2Deg * rad;
			tempVec.Set(0f, szog, 0f);
			toRotate = Quaternion.Euler(tempVec);
		}
		if(transform.rotation.y != toRotate.y)
		    transform.rotation = Quaternion.Lerp(transform.rotation, toRotate, speed * Time.deltaTime);
	}

}

This code probably won’t do what you want: the cosine don’t tell whether the target is at left or right, and you’re comparing rotation.y to toRotate.y in order to control the loop - the quaternion XYZW components have nothing to do with the Euler angles (actually, XYZ in a quaternion are a coded version of the rotation axis). It would be better to use more Quaternion functions as follows:

using UnityEngine;
using System.Collections;
 
public class EszrevetelScript: MonoBehaviour {

    public float error = 2.0f; // max error in degrees 
    public float speed = 0.05f; // too small! Try 1.0 to 10.0
    private Transform other;
    private Quaternion toRotate;
    private Vector3 distance;
 
    // Use this for initialization
    void Start () {
        other = GameObject.Find ("CylinderTwo").transform;
        // initialize toRotate to current rotation:
        toRotate = transform.rotation;
    }
 
    // Update is called once per frame
    void Update () {
        if(Input.GetKeyDown(KeyCode.A))
        { // define target rotation (other is a Transform!)
          distance = other.position - transform.position;
          distance.y = 0; // consider only the horizontal direction
          toRotate = Quaternion.LookRotation(distance);
        }
        // rotate to target direction until inside error margin:
        if (Quaternion.Angle(transform.rotation, toRotate) > error)
            transform.rotation = Quaternion.Lerp(transform.rotation, toRotate, speed * Time.deltaTime);
    }
}