【发布时间】:2015-09-03 19:27:14
【问题描述】:
我意识到我的数据溢出存在问题,但我主要关心的是尝试在最后重新运行程序以重新开始。我通过这个网站浏览了多个示例,但找不到真正适合我需要的示例。
我不确定你是否可以看到我的代码的第一部分,但我基本上尝试使用别人做的例子来做我的程序,但我就是想不通。
如果有人可以提出任何建议,我将不胜感激!
我敢肯定,如果我坚持下去,我最终会弄明白的,但我认为这对这个网站来说是个好问题。
这是我的源代码:
#include <stdio.h>
int main (void) {
int days;/* user will input number of days light will travel*/
int answer;
char buffer[256];
printf(" \n" );
printf("\t**-**-**-**Welcome to the LIGHT RAY!**-**-**-**\n");
printf(" \n" );
printf("\tTo get an idea of how unbelieveably fast light is!\n");
printf("\t come climb aboard the LIGHT RAY!\n", );
do
{
printf(" \n" );
printf(" \n");
printf("\tHow many days would you like to travel?\n");
scanf("%d", &days);
printf("processing...\n" ) /* fictional terminal computing information*/;
sleep(2);
printf("Initializing warp drive...\n" );
sleep(1);
printf("3\n" ) /* count down sequence*/;
sleep(1);
printf("2\n" );
sleep(1);
printf("1\n" );
sleep(1);
printf("SHROOOOM!\n" );
sleep(1);
int day_time=days * 86400/*86,400 seconds is equal to 1 day*/;
int distance=day_time*186000/*light travels 186,000 miles per second!*/;
printf("Congratulations, you have traveled %lld miles! \n",distance);
printf("Would you like another go?(yes, no)\n" );
scanf("%s\n", buffer );
}while (strcmp(buffer, "yes") !=0);
getchar();
return 0;
}
【问题讨论】:
-
您应该在编译时出现完整警告(gcc 上的
-Wall -Wextra -Wpedantic),并修复所有警告。另外:要在 gcc 上获得良好的警告,您还需要将其设置为优化 (-O3)。 -
不要使用
int使用double,因为86400 * 186000已经超出 32 位有符号整数的范围 1 天,更不用说一年了。 -
while (strcmp(buffer, "yes") !=0)应该测试==0以匹配字符串。 -
@WeatherVane 为什么使用
double而不是long long或(甚至更好)uint64_t?如有必要,无需引入凌乱的浮点数:) -
不要在此处使用
scanf ("%s\n", buffer)- 使用fgets (buffer, 255, stdin)以确保安全(并避免缓冲区溢出)。请注意,fgets会自动将 NULL 字符附加到输入中,因此我们使用 255 而不是 256 为其留出空间。