链表输入类型问题
linked list input type problems
我有这样的代码,要求用户输入一个数字,让程序知道我的链表有多大,然后下一个用户输入的将是推送到链接中的数据。我对整数没有问题,但无论出于什么原因,一旦我开始使用小数点,例如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
。
相关文章:
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 指针问题:从不兼容的类型"int"分配给"int *"
- 特征返回类型的 pybind11 问题
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 使用泛型类型推送到堆栈时出现问题
- 在点云库 (PCL) 中使用自定义点类型的问题
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 为<vtkDataArray> VTK 非结构化网格声明 vtkSmartPointer 类型的变量时出现问题
- 模板<类型名称...参数>的问题
- 类型转换问题
- GLUT 问题:重新声明 c++ 内置类型'wchar_t'时出错
- printf 数据类型说明符复杂问题
- 缺少类型说明符和另一个问题
- 拆分 pybind11 模块和自动类型转换问题
- 类型转换问题:返回为整数而不是浮点/类型
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 我的 SWIG 类型图有什么问题?
- 从标准输入读取多个类型时出现问题