【发布时间】:2016-09-29 02:30:25
【问题描述】:
我有这段代码,要求用户输入一个数字,让程序知道我的链接列表有多大,然后下一个用户输入将是推送到链接中的数据。我对整数没有任何问题,但是无论出于何种原因,一旦我开始使用小数点,例如 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); -
scanfis 类型不安全。不过,如果您使用 g++ 编译,您会得到“警告:格式 '%d' 需要 'int' 类型的参数,但参数 2 的类型为 'double'”。不要修复格式规范,而是删除所有 C 级 i/o 并使用cin和cout。