【问题标题】:How to do this assignment in C? Part 2如何在 C 中完成这项作业?第2部分
【发布时间】:2013-10-13 17:18:02
【问题描述】:

以下提示输入半径和高度,并使用这些值来计算圆柱体的体积。如何编写此程序,以便在用户为任一高度半径输入负值时它不会终止?范围必须是 1-10(含),并且不允许其他提示。只有在输入非数字内容时才必须终止循环。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


float areaCirc(float r){
return (M_PI*r*r);
}

float volCyl(float r, float h){
return (areaCirc(r)*h);
}


int main(void) {
float r, h;
int k = 0;
float volume;
float avgh = 0;
float toth = 0;

do{
    float exit = scanf("%f%f", &r, &h);
    if (exit == 0) 
    {break;}
    if(r<=0 || r>10){
        printf("Invalid radius: %.2f\n",r);
    }
    if(h<=0 || h>10){
        printf("Invalid height: %.2f\n",h);
    }
    if(r>=0 && r<=10 && h>=0 && h <= 10){
    volume = volCyl(r,h);
    k = k++;
    printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume);
    toth = toth + h;
} }while(r>0 && h>0);
    avgh = toth/k;
    printf("Total Height: %.2f\n",toth);
    printf("Average Height: %.2f\n",avgh);

return EXIT_SUCCESS;
}

【问题讨论】:

    标签: c terminate


    【解决方案1】:

    查看 while() 中的语句。请注意,当且仅当这些条件为真时,这将继续循环。

    【讨论】:

    • 我知道,但我不知道如何使它包含范围内的所有值,即负值和包含零的值
    【解决方案2】:
    do {
        printf("Enter radius: ")
        scanf("%d", &r);
        printf("Enter height: ")
        scanf("%d", &h);
    } while(r<=0 || h<=0);
    

    您可以使用 do-while 循环,不断提示用户重新输入半径和高度值小于或等于 0。

    希望这会有所帮助:)

    【讨论】:

      【解决方案3】:

      我指定的范围必须是 1 到 10 (含),没有负值终止程序,并且不允许其他提示

      修改你的主函数

      do{
          int ex = scanf("%f%f", &r, &h); //scanf returns int
      
         if (ex == 0)
          {break;}
          if(r<=0 || r>10){
              printf("Invalid radius: %.2f\n",r);
             continue;
          }
          if(h<=0 || h>10){
              printf("Invalid height: %.2f\n",h);
             continue;
          }
         // hence above conditions failed means you have given desired input
         // need not to check any conditions 
          volume = volCyl(r,h);
          k = k++;
          printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume);
          toth = toth + h;
         }while(r>0 && h>0);
      
        if(k>0) // check this other wise divide by zero will occur
          {
          avgh = toth/k;
          printf("Total Height: %.2f\n",toth);
          printf("Average Height: %.2f\n",avgh);
          }
      

      【讨论】:

      • 我指定的范围必须是1到10(含),没有负值终止程序,也不允许其他提示
      • 当用户输入 11 或 -1 作为输入时是否要打印错误。我的意思是 1-10 范围内
      • 我想打印无效的半径或无效的高度,如果它们超出范围,并在没有文本引导的情况下继续提示输入,并且循环仅在输入非数字时终止。
      • @user2805620 相应地修改了答案。
      • 程序在输入负值后仍然终止。它是我不知道如何改变的同时做的条件
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多