gpt4 book ai didi

c++ - 没有从等式中得到正确的答案。还有,无限循环

转载 作者:行者123 更新时间:2023-11-27 23:08:31 25 4
gpt4 key购买 nike

好的,所以我应该计算如果我以一定的速度和持续时间以光速行进,会经过多少时间。是的,这是作业。我已经弄清楚了大部分,但是当我输入 40 的时间和 60 的年份时,我得到 0.008305 而我应该得到 50。这是怎么回事?

此外,do while 循环无法正常工作。无论我如何回答,它都会重复整个代码块并忽略 cout 和 cin 语句,导致它在评估 v1 时给我错误。我该如何解决这个问题?

#include <iostream>
#include <iomanip>
#include <conio.h>
#include <cmath>

const int c = 299792458;

int main()
{
int loopCheck = 'y';

do
{
int tm = 0;

std::cout << "Enter time of travel: " << std::endl;
std::cin >> tm;

if (tm < 0)
{
do
{
std::cout << "You have entered an incorrect value. "
<< "Please enter a value greater than 0."
<< std::endl;
std::cin >> tm;

} while (tm < 0);
}

double v1 = 0;

std::cout << "Enter velocity: " << std::endl;
std::cin >> v1;

if (v1 <= 0 || v1 >= 100)
{
do
{
std::cout << "You have entered an incorrect value. "
<< "Please enter a value between 0 and 100."
<< std::endl;
std::cin >> v1;

} while (v1 <= 0 || v1 >= 100);
}

double v2 = (v1 / 100) * c;
double ts = tm / (sqrt((1 - (v2 * v2))/(c * c)));

std::cout << v2 << " " << c << std::endl;

std::cout << std::fixed << std::setprecision(6) << ts
<< std::endl << std::endl;

std::cout << "Would you like to enter more data? (y/n)" << std::endl;
std::cin >> loopCheck;
} while (loopCheck == 'y');

_getch();
return 0;
}

最佳答案

循环总是重复,因为你输入了一个字符 yn 并且声明了 loopCheck

int loopCheck = 'y';

这意味着,

std::cin >> loopCheck;

寻找整数,但找不到。根据编译器的版本,loopCheck 将保持不变或设置为零,请参阅 `std::basic_istream::operator>> .如果将其更改为

char loopCheck = 'y';

它应该按预期工作。

修复

中的整数溢出问题
double ts = tm / (sqrt((1 - (v2 * v2))/(c * c)));

您可以将 c 声明为 double,例如

const double c = 299792458;

更新:

公式中还有一个额外的错误。你有

sqrt((1 - v2²) / c²)

给出负数,因此是错误的。删除括号

sqrt(1 - v2² / c²)

转化为

double ts = tm / (sqrt(1 - (v2 * v2) / (c * c));

给出正确的输出。

关于c++ - 没有从等式中得到正确的答案。还有,无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666618/

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