我的代码第一次工作,当循环开始时,它停止计算数字!
我希望程序在每次完成计算数字时要求用户选择材料。我用while(1!= 2){}
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
float stress, strain, area;
double diameter;
long int F = 9900;
const float pi = 3.141593f;
int i = 0;
int main() {
char meterial;
cout << "This programm calculates the stress and strain of a rod under loads from 10000N to 20000N\n\n";
while (1!=2)
{
cout << "Choose the meterial of the rod\n\n";
cout << "S For STEEL\nA For ALUMINUM\nC For COPPER\nT For TITANIUM\n\n";
cin >> meterial;
switch (meterial)
{
case 's':
cout << "\nEnter the diameter of the rod in mm: ";
cin >> diameter;
area = (pi * diameter * diameter) / 4;
while (i <= 50)
{
stress = F / area;
strain = 200 / stress;
F = F + 100;
cout << "Load = " << F << " Stress = " << stress << " N/mm^2" << " Strain = " << strain << "\n";
i++;
}
break;
case 'a':
cout << "Enter the diameter of the rod in mm: ";
cin >> diameter;
area = (pi * diameter * diameter) / 4;
while (i <= 50)
{
stress = F / area;
strain = 69 / stress;
F = F + 100;
cout << "Load = " << F << " Stress = " << stress << " N/mm^2" << " Strain = " << strain << "\n";
i++;
}
break;
case 'c':
cout << "Enter the diameter of the rod in mm: ";
cin >> diameter;
area = (pi * diameter * diameter) / 4;
while (i <= 50)
{
stress = F / area;
strain = 117 / stress;
F = F + 100;
cout << "Load = " << F << " Stress = " << stress << " N/mm^2" << " Strain = " << strain << "\n";
i++;
}
break;
case 't':
cout << "Enter the diameter of the rod in mm: ";
cin >> diameter;
area = (pi * diameter * diameter) / 4;
while (i <= 50)
{
stress = F / area;
strain = 110.3 / stress;
F = F + 100;
cout << "Load = " << F << " Stress = " << stress << " N/mm^2" << " Strain = " << strain << "\n";
i++;
}
break;
default:
cout << "You entered a wrong character";
}
}
}
答案 0 :(得分:0)
在下次通话之前,我没有看到您重置i的值。
但你真的应该在某个函数或方法中循环(while(i <= 50)),除非你已经研究过那些。
答案 1 :(得分:0)
变量i
永远不会重新初始化为零。如果你更换每个
while (i <= 50)
在switch
语句的情况下使用类似的语句声明
for (int i = 0; i <= 50; ++i)
并删除每个相应块中的i++;
行,例如
case 's':
cout << "\nEnter the diameter of the rod in mm: ";
cin >> diameter;
area = (pi * diameter * diameter) / 4;
for (int i = 0; i <= 50; ++i) // while (i <= 50) <-- change
{
stress = F / area;
strain = 200 / stress;
F = F + 100;
cout << "Load = " << F << " Stress = " << stress << " N/mm^2" << " Strain = " << strain << "\n";
// i++; <-- remove
}
您的代码应该按照您的期望进行。您可以考虑将while (1!=2)
测试替换为while(1)
或for(;;)
之类的内容,但这仅仅是因为这些是更常见的习惯用法(您的测试将始终评估为true
所以它&#39} ; s还是很好。)
开启编辑:还有一件事 - 您永远不会重新初始化 F
,但您需要在计算中对其进行修改。每次执行switch
声明时,您都会以 F
的不同初始值开头。