gpt4 book ai didi

c - scanf 不能很好地处理我的结构代码

转载 作者:行者123 更新时间:2023-11-30 14:59:26 26 4
gpt4 key购买 nike

我正在做 Steven G.Kochan 所著的《Programming in C》一书,第三版中的练习。目前正在研究第 9 章 - 使用结构。问题的主要部分如下,问题中提供了代码中的公式:

Write a program that permits the user to type in two dates and then calculates the number of elapsed days between the two dates.Try to structure the program logically into separate functions. For example, you should have a function that accepts as an argument a date structure and returns the value of N. This function can then be called twice, once for each date, and the difference taken to determine the number of elapsed days.

我编写的代码也在下面......但它没有按预期工作:我附有一张图像作为证据,请帮我找出问题是什么 output screen showing that it doesn't allow me enter the second date.

#include <stdio.h>
struct date
{
int day;
int month;
int year;
};

//function declarations
int f (struct date thisDate);
int g (struct date thisDate);

int main(void)
{


//declarations and initializations
struct date theDate, otherDate;
int N1, N2, days;



printf("Enter the first Date (dd/mm/yyyy):");
scanf("%i/%i/%i", &theDate.day, &theDate.month, &theDate.year);

// compute N1
N1 = (1461 * f(theDate) ) / 4 + (153 * g(theDate)) / 5 + 3; //this can be replaced with a function


printf("\nEnter the second Date (dd/mm/yyyy):");
scanf("%i/%i/%i", &otherDate.day, &otherDate.month, &otherDate.year);

// compute n2
N2 = (1461 * f(otherDate) ) / 4 + (153 * g(otherDate)) / 5 + 3; //this can be replaced with a function

days = N2 - N1;
printf("\nThere are %i days between these two dates",days);

return 0;
}

int f (struct date thisDate)
{
if (thisDate.month <= 2)
{
return thisDate.year - 1;
}
else
{
return thisDate.year;
}
}

int g (struct date thisDate)
{
if ( thisDate.month <= 2)
{
return thisDate.month + 13;
}
else
{
return thisDate.month + 1;
}
}

最佳答案

看图片,输入字符串是03/09/2007;第二个输入在进行计算之前不会等待输入任何新内容。

问题是您使用了读取八进制、十六进制或十进制数的%i。八进制数由前导零表示;因此,09 会转换为月份的 0(因为 9 不是有效的八进制数字;08 也会出现问题),然后转换失败(0 之后没有 /。下一个输入以 92007 开头,然后不'找不到 / 所以它就停止了。

多重道德:

  1. 检查 scanf() 的返回值。在此代码中,确保它返回 3;如果没有,则说明出了问题。
  2. 不要使用%i读取日期值;使用%d。人们不使用八进制,但有时会输入 09(和 08)。
  3. 验证您读到的数字。将它们打印出来很有帮助——它可以让您查看程序是否得到了您期望的结果。

关于c - scanf 不能很好地处理我的结构代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42745884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com