【问题标题】:linked list input type problems [duplicate]链表输入类型问题[重复]
【发布时间】: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", &amp;x); 应该是scanf_s("%lf", &amp;x);
  • scanfis 类型不安全。不过,如果您使用 g++ 编译,您会得到“警告:格式 '%d' 需要 'int' 类型的参数,但参数 2 的类型为 'double'”。不要修复格式规范,而是删除所有 C 级 i/o 并使用 cincout

标签: c++ types


【解决方案1】:
scanf_s("%d", &x); 

应该是

scanf_s("%lf", &x);

%d 用于读取十进制整数。 %lf 代表reading in a long floating point number,即double

【讨论】:

  • 那应该是%lf,因为它是双倍的。
  • @KenY-N:不。但它应该是标准的scanf,而不是微软的scanf_s。但是,更好的是,它应该替换为 C++ iostreams i/o。
  • @Cheersandhth.-Alf 检查 dup 中的 not accepted answerthis link - 都说 %lf
  • 感谢大家的帮助。我将结构节点和变量 x 更改为将数据作为浮点类型而不是双精度以及使用 scanf("%f", &x);当打入数字和最后 printf(" %.8f", temp->data); 8 位小数。它现在像冠军一样工作。 Ken Y-N,感谢您提供其他答案提交的链接,:D
  • @KenY-N:谢谢,你是对的。这是我忘记的 printf 和 scanf 之间的一点不一致。自从使用 scanf 多年以来。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 2011-04-05
相关资源
最近更新 更多