【问题标题】:How can I get a different statement printed to the user each loop iteration?如何在每次循环迭代时向用户打印不同的语句?
【发布时间】:2022-01-08 13:14:22
【问题描述】:

如何让我的代码在 for 循环中向用户显示不同的打印语句?代码的目标是在知道其他两条边的情况下求解直角三角形的未知边。

我的代码按预期工作,但是没有关于用户将在哪一侧输入值的指南。有什么办法可以让打印语句显示用户将在 for 循环中为哪一侧输入值?

例如:在循环的第一次运行期间,代码将显示“为 A 面输入值”,然后下一次运行将显示“为 B 面输入值”,最后一次运行将显示“为 A 面输入值” C 面”。

#define _CRT_SECURE_NO_WARNINGS
#include <math.h>
#include <stdio.h>

float TriSideSolver(float side1, float side2, float side3, float* ptrA, float* ptrB, float* ptrC);
void main(void)
{
    float inputA, inputB, inputC; // needed variables
    int success;
    int i;
    float known[3]; 
    float A, B, C;
    printf("Input the known sides of the triangle, enter zero for the unknown side\n"); // prints instructions to user
    for (i = 0; i < 3; i++) // for loop assigning values to the sides of the triangle.
    {
        scanf("%f", &known[i]);
    }
    A = known[0]; // assign inputs to variables
    B = known[1];
    C = known[2];

    success = TriSideSolver(A, B, C, &inputA, &inputB, &inputC); // call to use function.

    A = inputA; // assign new values to variables
    B = inputB;
    C = inputC;
    printf("These are the results:\n A= %f\n B= %f\n C= %f\n", A, B, C); // print values to the user 

}//end of main

float TriSideSolver(float side1, float side2, float side3, float* ptrA, float* ptrB, float* ptrC)
{ 
    if (side1 == 0)
    { // need to find side A
        *ptrA = sqrt((pow(side3, 2)) - (pow(side2, 2)));
        *ptrB = side2;
        *ptrC = side3; 
        return 1;
    }
    else if (side2 == 0)
    {// need to find side B
        *ptrB = sqrt((pow(side3, 2)) - (pow(side1, 2)));
        *ptrA = side1;
        *ptrC = side3;
        return 1;
    }
    else if (side3 == 0)
    {// need to find side C
        *ptrC = sqrt((pow(side1, 2)) + (pow(side2, 2)));
        *ptrA = side1;
        *ptrB = side2;
        return 1;
    }
    else //if user inputs 3 sides
    {
        *ptrA = side1;
        *ptrB = side2;
        *ptrC = side3;
        return 1;
    }

}//end of function

【问题讨论】:

    标签: c for-loop printf


    【解决方案1】:

    您可以将边的名称存储在字符数组中,并在循环中以正确的顺序打印它们。

    一个最小的例子是:

    #include <stdio.h>
    
    int main()
    {
        float known[3];
        char side_names[] = {'A', 'B', 'C'};
        int i = 0;
    
        for (i = 0; i < 3; i++) // for loop assigning values to the sides of the triangle.
        {
            printf("Input the length of side: %c\n", side_names[i]);
            scanf("%f", &known[i]);
        }
    }
    

    这里side_names 存储代表每一边的字符,它们在循环中被收集的顺序相同。请注意,如果您要存储字符串,情况会有所不同。

    【讨论】:

    • 感谢您的帮助,这就像一个魅力!
    • 不客气! :)
    猜你喜欢
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多