链表输入类型问题

linked list input type problems

本文关键字:问题 类型 输入 链表      更新时间:2023-10-16

我有这样的代码,要求用户输入一个数字,让程序知道我的链表有多大,然后下一个用户输入的将是推送到链接中的数据。我对整数没有问题,但无论出于什么原因,一旦我开始使用小数点,例如32.22,程序就会停止正常执行,并将数字保留在带小数点的数字的左侧,并将相同的数字添加到其他节点。仅供参考,我正在Visual Studio Express 2012中进行开发。

对于一个好的执行,使用3作为数据的数量,分别使用数字1、2、3,我得到以下输出:

How many numbers?
3
Please enter number
1
List is: 1
Please enter number
2
List is: 2 1
Please enter number
3
List is: 3 2 1
Press any key to continue . . . _

对于糟糕的输出,我得到的是:

How many numbers?
3
Please enter number
1
List is: 1
Please enter number
23.23
List is: 23 1
Please enter number
List is: 23 23 1
Press any key to continue . . . _

这是我的代码:

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using std::cout;
using std::cin;
using std::endl;
 struct Node
{
    double data;
    Node* next;
    };
struct Node* head; // global variable
void Insert(double x)
{
    Node* temp = new Node;
    temp->data = x;
    temp->next = NULL;
    if(head != NULL) temp->next = head; 
    head = temp;
}
void Print()
{
Node* temp = head;
printf("List is: "); 
while(temp != NULL)
{
    printf(" %d", temp->data);
    temp = temp->next;
}
printf("n");
}
int main()
{
head = NULL; // empty list
printf("How many numbers?n");
int n, i;
double x;
scanf_s("%d", &n);
for(i = 0; i < n; i++)
{
    printf("Please enter number n");
    scanf_s("%d", &x);
    Insert(x);
    Print();
}
system("PAUSE");
    return 0;
}

对此有什么建议或建议吗?让我头疼的是,代码对整数非常有效,但一旦我开始引入小数点,它就会变得疯狂。我已经尝试将用户输入和节点结构中的数据类型转换为int类型和double类型,并且使用这两种类型都得到了相同的结果。

scanf_s("%d", &x); 

应该是

scanf_s("%lf", &x);

%d用于读取十进制整数。%lf用于读取长浮点数,即double